文章目录
- @Component
- @Bean
- @import
- @import搭配importSelector
- @import搭配importBeanDefinitionRegistrar
- BeanFactoryPostProcessor
@Component
- 第一种方式是@Component方式,标志这个类是一个Bean对象
- 要放在启动类的目录或者子目录下,不然需要在加上@ComponentScan来扫描
- 通过加在类上实现
@Component
class Test{
}
- 还有同等注解@Controller加在控制层,@Service服务层,@Repository持久层,@Configuration配置类,因为他们都使用了@Component
@Bean
- 第二种@Bean,这个注解要加在方法上,然后返回值是要实例化的类
//必须先让这个类被springboot扫描到@Bean才会起作用
@Configuration
class Test{
@Autowired
TestClass testClass;
//返回了实例那么这个实例会被springboot所管理
@Bean
public TestClass getTestClass(){
return new TestClass();
}
@PostConstruct
public void print(){
System.out.println(testClass);
}
}
class TestClass{
}
@import
- 第三种@import注解,可以直接导入想要被springboot管理的类
@Configuration
//value是一个数组,可以写多个class。比如a.class,b.class
@import(TestClass.class)
class Test{
@Autowired
TestClass testClass;
@PostConstruct
public void print(){
System.out.println(testClass);
}
}
class TestClass{
}
@import搭配importSelector
- 第四种@import搭配importSelector,实现importSelector的方法实例化多个bean
@Configuration
@import(TestClass.class)
class Test{
@Autowired
TestSelectimports testSelectimports;
@PostConstruct
public void print(){
System.out.println(testSelectimports);
}
}
//TestClass类似于一个实例化类的工具类,自身不会被springboot所管理
class TestClass implements importSelector {
//返回值是一个字符串数组,也是需要类的全类名
@Override
public String[] selectimports(Annotationmetadata importingClassmetadata) {
return new String[]{TestSelectimports.class.getName()};
}
}
class TestSelectimports{
}
@import搭配importBeanDefinitionRegistrar
- 第五种是@import搭配importBeanDefinitionRegistrar,实现这个接口的方法会交给我们一个BeanDefinitionRegistry,实现这个接口的都是工厂类,所以就是我们可以直接通过这个接口的方法把bean直接注册到工厂中
@Configuration
@import(TestClass.class)
class Test{
@Autowired
TestSelectimports testSelectimports;
@PostConstruct
public void print(){
System.out.println(testSelectimports);
}
}
class TestClass implements importBeanDefinitionRegistrar {
//Annotationmetadata是谁导入了这个类也就是Test类
//BeanDefinitionRegistry可以简单理解成Bean工厂,然后可以直接注册Bean
//每个Bean都会被转换成BeanDefinition,里边包含了Bean的所有元数据信息
@Override
public void registerBeanDefinitions(Annotationmetadata importingClassmetadata, BeanDefinitionRegistry registry) {
registry.registerBeanDefinition("testSelectimports",new RootBeanDefinition(TestSelectimports.class));
}
}
class TestSelectimports{
}
BeanFactoryPostProcessor
- 第六种我们可以实现BeanFactoryPostProcessor接口,他会返回给我们一个BeanFactory,我们可以任意操作,这是spring的一个扩展点,可以让我们在实例化Bean之前对元数据信息进行任意修改
@Component
class TestBeanFactory implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
//这个接口只有两个实现类,一个XmlFactory现实了DefaultListableBeanFactory并且被标记为废弃了
//所以把它转换成子类,功能更多
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
//直接向工厂注册Bean
defaultListableBeanFactory.registerBeanDefinition("testSelectimports",new RootBeanDefinition(TestSelectimports.class));
}
}
class TestSelectimports{
}