一、
Bean的装配 Bean的装配,即Bean对象的创建。
1 默认装配方式(构造方式)
2 动态工厂Bean
3 静态工厂Bean
二、代码实现
appilcationContext.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 id="someServiceImpl" class="com.facai.service.Impl.SomeServiceImpl"></bean>
<!-- 动态工厂:注册工厂 -->
<bean id="serviceFactory" class="com.facai.service.factory.ServiceFactory"></bean>
<!-- 从工厂中获取someServiceImpl的bean对象 -->
<bean id="someServiceImpl2" factory-bean="serviceFactory" factory-method="getSomeService"></bean>
<!-- 静态工厂获取 -->
<bean id="staticSomeServiceImpl" class="com.facai.service.factory.ServiceFactory" factory-method="getStaticSomeService"></bean>
</beans>
工厂方法
package com.facai.service.factory;
import com.facai.service.SomeService;
import com.facai.service.Impl.SomeServiceImpl;
public class ServiceFactory {
//动态工厂创建bean方法
public SomeService getSomeService() {
SomeService service=new SomeServiceImpl();
return service;
}
//静态工厂创建bean方法
public static SomeService getStaticSomeService() {
SomeService service=new SomeServiceImpl();
return service;
}
}
测试类
@Test
public void someTest1() {
//创建容器对象,ApplicationContext初始化时,所有的容器中的bean创建完毕
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService service=ac.getBean("staticSomeServiceImpl", SomeService.class);
service.doSome();
}
BeanFactory和ApplicationContext获取bean对象的区别
@Test
public void someTest1() {
//创建容器对象,ApplicationContext初始化时,所有的容器中的bean创建完毕
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService service=ac.getBean("staticSomeServiceImpl", SomeService.class);
service.doSome();
}
@Ignore
@Test
public void someTest2() {
//创建容器对象,BeanFactory调用getBean获取响应对象时,才创建对象
BeanFactory ac=new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
SomeService service=ac.getBean("someServiceImpl", SomeService.class);
service.doSome();
}
当将断点设置在
SomeService service=ac.getBean(“staticSomeServiceImpl”, SomeService.class);时
有输出
当将断点设置在
SomeService service=ac.getBean(“someServiceImpl”, SomeService.class);时
无输出