南开小巷

导航

Spring中注入bean学习的总结

1.在类上直接加注解@Component,那么这个类就直接注入到Spring容器中了  ,像@Contrloller,@Service这些本质上都是@Component,

2.@Configuration(或者@SpringBootConfiguration)放到类上,然后在类中的方法上加注解@Bean

@SpringBootConfiguration
public class UseConditionalOnBean {

@Bean
public User createBean(){
return new User();
}
}

当然也可以直接在类上加@Bean,这种情况就和1比较类似了

3.@ComponentScan (在主类中,比如springboot的App.java),然后在加上@Import(Bean.class)或者@Import(BeanConfig.class)

4.@ComponentScan (在主类中,比如springboot的App.java),然后在@EnableXXX 这个注解里也是包含有@Import,本质上还是和3一样

 

再说,Bean注入Spring容器的一些回调:

1.DefinitionRegistryPostProcessor:

/**
* 通过BeanDefinitionRegistryPostProcessor动态的注入bean
* 这里的例子是一次性注入10个person的bean,并为这10个person的bean的name属性赋值了
* BeanDefinitionRegistryPostProcessor可以拿到ConfigurableListableBeanFactory和BeanDefinitionRegistry两个对象
* @author Joy
*
*/

@Component
public class MyBeanDefinitionRegistryPostProcessor implements
BeanDefinitionRegistryPostProcessor {

public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {

}

public void postProcessBeanDefinitionRegistry(
BeanDefinitionRegistry registry) throws BeansException {
for(int i=1;i<=10;i++){
BeanDefinitionBuilder bdb=BeanDefinitionBuilder.rootBeanDefinition(Person.class);//这个是构造beanDefinition的
bdb.addPropertyValue("name", "admin"+i);
registry.registerBeanDefinition("person"+i, bdb.getBeanDefinition());
}
}

}

2.BeanFactoryPostProcessor

/**
* 容器初始化的回调方法
* BeanFactoryPostProcessor在spring容器初始化之后触发,而且只会触发一次
* 触发的时机比BeanPostProcessor早
* @author Joy
*
*/
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
System.out.println("=========postProcessBeanFactory========"+ beanFactory.getBeanPostProcessorCount());
}

}

 

3.BeanPostProcessor:

/**
* Bean初始化的回调方法
* @author Joy
*
*/

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
System.out.println("++++++++before+++++"+bean.getClass());
return bean;
}

public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
System.out.println("----------after----"+bean.getClass());
return bean;
}

}

posted on 2017-10-13 17:23  南开小巷  阅读(244)  评论(0编辑  收藏  举报