茴香豆的四种写法。。
----声明bean----
1.@Component 声明普通bean
2.@Component 声明FactoryBean
@Component
public class MyFactory implements FactoryBean<MytestBean> {
@Override
public MytestBean getObject() throws Exception {
return new MytestBean();
}
@Override
public Class<?> getObjectType() {
return MytestBean.class;
}
}
3.在配置类中使用@Bean
@Configuration
public class MyConfig {
@Bean
public Mytestbean create(){}
}
----手动注册BeanDefinition----
4.使用BeanDefinitionRegistryPostProcessor注册BeanDefinition
@Component
public class MyBeanRegister implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MytestBean.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("age", "25");
registry.registerBeanDefinition("mytestBean", beanDefinition);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
5.使用@Import + ImportBeanDefinitionRegister注册BeanDefinition
public class MyBeanImport implements ImportBeanDefinitionRegistrar{
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(MytestBean.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("age", "25");
registry.registerBeanDefinition("mytestBean", beanDefinition);
}
}
在Bootstrap启动类或者一个配置类中使用:
@Import(MyBeanImport.class)
6.引入xml配置文件,除了老项目升级基本上不用,没啥好说的
不同注册方式执行的顺序不同,总体上顺序:ImportBeanDefinitionRegister > BeanDefinitionRegistryPostProcessor > @Bean = @Component
如果用注册FactoryBean<MyBean>的方式来提供bean的话,Spring并不能管理好依赖的先后顺序,所以如果依赖MyBean的bean先被spring装配,就会出现找不到bean的情况,这时候可以让bean同时依赖对应的FactoryBean以确保FactoryBean被先注册。