一、Bean的装配
bean的装配,即Bean对象的创建,容器根据代码要求来创建Bean对象后再传递给代码的过程,称为Bean的装配。
二、默认装配方式
代码通过getBean()方式从容器获取指定的Bean示例,容器首先会调用Bean类的无参构造器,创建空值的示例对象。
三、工厂方法设计模式(为了解耦合)
1 public class ServiceFactory { 2 public ISomeService getISomeService(){ 3 return new SomeServiceImpl(); 4 } 5 }
@Test public void test01() { ISomeService service=new ServiceFactory().getISomeService(); service.doSome(); }
静态工厂
public class ServiceFactory { public static ISomeService getISomeService(){ return new SomeServiceImpl(); } }
@Test public void test01() { ISomeService service=ServiceFactory.getISomeService(); service.doSome(); }
四、动态工厂Bean
public class ServiceFactory { public ISomeService getSomeService(){ return new SomeServiceImpl(); } }
<!--注册动态工厂 --> <bean ></bean>
@SuppressWarnings("resource")
@Test
public void test02() {
//创建容器对象
String resource = "com/jmu/ba02/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ServiceFactory factory=(ServiceFactory) ac.getBean("factory");
ISomeService service = factory.getSomeService();
service.doSome();
}
但以上方法不好。修改如下(测试类看不到工厂,也看不到接口的实现类)
<!--注册service:动态工厂Bean-->
<bean ></bean>
@SuppressWarnings("resource")
@Test
public void test02() {
//创建容器对象
String resource = "com/jmu/ba02/applicationContext.xml";
ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
五、静态工厂Bean
public class ServiceFactory { public static ISomeService getSomeService(){ return new SomeServiceImpl(); } }
<!--注册动态工厂 :静态工厂Bean-->
<bean ></bean>
@Test @SuppressWarnings("resource") public void test02() { //创建容器对象 String resource = "com/jmu/ba03/applicationContext.xml"; ApplicationContext ac=new ClassPathXmlApplicationContext(resource); ISomeService service = (ISomeService) ac.getBean("myService"); service.doSome(); }
六、Bean的装配
1、Singleton单例模式:
2、原型模式prototype:
3、request:对于每次HTTP请求,都会产生一个不同的Bean实例
4、Session:对于每次不同的HTTP session,都会产生一个不同的Bean实例
七、Bean后处理器
bean后处理器是一种特殊的Bean,容器中所有的Bean在初始化时,均会自动执行该类的两个方法,由于该Bean是由其他Bean自动调用执行,不是程序员手动创建,所有Bean无需id属性。
需要做的是,在Bean后处理器类方法中,只要对Bean类与Bean类中的方法进行判断,就可以实现对指定的Bean的指定方法进行功能扩展和增强。方法返回的Bean对象,即是增强过的对象。
代码中需要自定义Bean后处理下类,该类就是实现了接口BeanPostProcessor的类。该接口包含2个方法,分别在目标Bean初始化完毕之前和之后执行,它们的返回值为:功能被扩展或增强后的Bean对象。
1 import org.springframework.beans.BeansException; 2 import org.springframework.beans.factory.config.BeanPostProcessor; 3 4 public class MyBeanPostProcessor implements BeanPostProcessor { 5 //bean:表示当前正在进行初始化的Bean对象 6 //beanName:表示当前正在进行初始化的Bean对象的id 7 @Override 8 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 9 // TODO Auto-generated method stub 10 System.out.println("执行before"); 11 return bean; 12 } 13 @Override 14 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 15 // TODO Auto-generated method stub 16 System.out.println("执行after"); 17 return bean; 18 } 19 20 21 }