Spring注解创建Bean的几种方式
Spring注解创建Bean的几种方式
1、@Component系列
@Component @Service @Repository @Controller @Configuration
2、 依附于@Configuration的注解
@Bean 创建Deom
@Configuration public class Demo { @Bean public Demo demo(){ return new Demo(); } }
@Import 创建Cofing
@Configuration @Import(Config.class) public class Demo { }
@Import.ImportSelector 选择器,传入@Import注解所在类Demo上所有的注解信息,返回要导入的类名
@Configuration @Import(ImportSelector_.class) public class Demo { } public class ImportSelector_ implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{"com.spring.demo.beanlifecycle.Demo"}; } }
@Impport.ImportBeanDefinitionRegistrar Bean定义注册器,传入@Import注解所在类Demo上所有的注解信息(1),Bean定义注册器(2)
//PS:Mybatis的Mapper接口就是用这种方式将Bean定义注册到Spring上下文的
@Configuration @Import(ImportBeanDefinitionRegistrar_.class) public class Demo { } public class ImportBeanDefinitionRegistrar_ implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Bean.class).setInitMethodName("init").setDestroyMethodName("destroy").getBeanDefinition(); registry.registerBeanDefinition("bean", beanDefinition); System.out.println("registerBeanDefinitions: " + beanDefinition); } }
3、FactoryBean
当通过“factoryBean”获取实例时,FactoryBean会调用getObject()方法
当通过“&factoryBean”获取实例时,返回FactoryBean的实例
当通过Demo.class来获取bean实例时,调用factoryBean的getObjectTyoe()来获取类型。
@Configuration public class Demo { @Bean public FactoryBean_ factoryBean(){ return new FactoryBean_(); } } public class FactoryBean_ implements FactoryBean { @Override public Object getObject() throws Exception { return new Demo(); } @Override public Class<?> getObjectType() { return Demo.class; } }