Spring-BeanFactory/ApplicationContect 女爷i 2021-09-24 10:40 297阅读 0赞 ### Spring-BeanFactory/ApplicationContect ### * 前情提要 * 核心API * 项目目录 * 项目代码 * * 配置文件xml * Java代码 * * 接口 * 实现类 * 测试类 * 结果 # 前情提要 # [IOC-XML配置][IOC-XML] # 核心API # ![Spring核心API][Spring_API] * BeanFactory: * Bean工厂,用于生产任意Bean * 采取延迟加载,第一次getBean时才会初始化Bean * ApplicationContect: * BeanFactory的子类,拓展提供了更多的功能 * 国际化处理 * 事件传递 * Bean自动装配 * 各种不同应用层的Context实现 * **ClassPathXmlApplicationContext**:用于加载类路径classpath(src文件夹)下的xml文件 * FileSystemXmlApplicationContext:用于加载指定盘符下的xml文件 # 项目目录 # ![Spring-BeanFactory/ApplicationContect][Spring-BeanFactory_ApplicationContect] # 项目代码 # ## 配置文件xml ## 常用名称:applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置bean --> <bean id="UserService" class="com.zhangzibu.spring.ioc.service.impl.UserServiceDi"></bean> </beans> ## Java代码 ## ### 接口 ### package com.zhangzibu.spring.ioc.service; public interface UserService { void hello(String para); } ### 实现类 ### package com.zhangzibu.spring.ioc.service.impl; import com.zhangzibu.spring.ioc.service.UserService; public class UserServiceDi implements UserService { @Override public void hello(String para) { System.out.println("Hello " + para); } public UserServiceDi(){ System.out.println("UserServiceDi------构造函数"); } } ### 测试类 ### package com.zhangzibu.spring; import com.zhangzibu.spring.ioc.service.UserService; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; public class SpringTest { @Test public void test(){ BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("/applicationContext.xml")); System.out.println("BeanFactory...."); UserService userServiceBeanFactory = (UserService) beanFactory.getBean("UserService"); userServiceBeanFactory.hello("BeanFactory 张子布"); System.out.println(" "); ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContext.xml"); System.out.println("ApplicationContext...."); UserService userServiceApplicationContext = (UserService) applicationContext.getBean("UserService"); userServiceApplicationContext.hello("ApplicationContext 张子布"); } } # 结果 # BeanFactory.... UserServiceDi------构造函数 Hello BeanFactory 张子布 UserServiceDi------构造函数 ApplicationContext.... Hello ApplicationContext 张子布 [IOC-XML]: https://mp.csdn.net/console/editor/html/105453586 [Spring_API]: /images/20210923/7983f6da870f43ec9591f0f9ef1e5327.png [Spring-BeanFactory_ApplicationContect]: /images/20210923/1914e724e2b34804bbf1da9153b5cd55.png
还没有评论,来说两句吧...