SpringFramework的手动装配
文章目录
装配组件有三种方式
- 使用模式注解 @Component 等(Spring2.5+)
@Component @Service @Controller @Repository 等作用在类上表示自动向IOC容器中注册bean
如下
@Component
public class BeanClass{
}
这几个注解在功能作用上都一样,但为了可读性表示分层效果各自不同表示各自的含义 如 @Controller 一般都作用在控制层,@Service 一般作用在业务类上等
- 使用配置类 @Configuration 与 @Bean (Spring3.0+)
@Configuration 和 @Bean 组合作用相当于下面xml方式 表示向ioc容器中注册一个bean
<bean id="bean" class="com.xx.Red2Color"/>
实例
@Configuration
public class ConfigrationBean {
@Bean("readColor2")
public Red2Color red2Color(){
return new Red2Color();
}
}
- 使用模块装配 @EnableXXX 与 @Import (Spring3.1+)
@EnableXXX 表示手动装配bean
@Import 表示向组件导入到指定配置类中
@Import 可以导入四种类型的bean
public @interface Import {
/**
* {@link Configuration @Configuration}, {@link ImportSelector},
* {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
*/
Class<?>[] value();
}
- @Configuration 注册的普通bean
- 实现ImportSelector接口的实体类
- 实现ImportBeanDefinitionRegistrar接口的实体类
- @component 等普通组件bean
示例:
首先自定义注解 @EnableBean
然后导入装配四种bean
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EnableBean {
}
创建实体类
public class RedColor {
}
public class Red2Color {
}
public class GreenColor {
}
public class YellowColor {
}
导入普通类
//导入 RedColor bean
@Import({RedColor.class})
导入ioc中的配置bean
配置类
@Configuration
public class ConfigrationBean {
@Bean("red2Color")
public Red2Color redColor(){
return new Red2Color();
}
}
导入装配
//导入配置类
@Import({ConfigrationBean.class})
导入实现了ImportSelector接口的bean
实现了ImportSelector接口的bean , 本身不需要注册到ioc容器中,可以在此实现类中 定义bean 将此类导入到指定配置类中,此定义的bean会被注册到ioc容器中
public class ColorImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{
//手动装配 : 在EnableBean类中 使用Import 注解 会将 GreenColor 会被注册到ioc容器中
// ColorImportSelector 类本身不会被注册到ioc容器中
GreenColor.class.getName()
};
}
}
导入ImportBeanDefinitionRegistrar 的实现类
此种方式可以自定义bean 的id
/**
* ImportBeanDefinitionRegistrar 的实现类
**/
public class EnableColorImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
//自定义需要导入ioc容器的Bean 可以自定义bean 名 , 在 EnableBean 手动配置类中 使用 @Import 导入
// EnableColorImportBeanDefinitionRegistrar 类本身也不会被注册到ioc容器中
//指定Bean的id
beanDefinitionRegistry.registerBeanDefinition("yellowColor",new RootBeanDefinition(YellowColor.class));
}
}
测试
手动装配到Ioc中
@EnableBean
//配置 bean
@Configuration
public class EnableColorConfigration {
}
获取ioc容器打印结果
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(EnableColorConfigration.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
//打印出ioc容器中所有注册bean的名字
Stream.of(beanDefinitionNames).forEach(System.out::println);
可以看到@Import 实现接口方式导入的2个类并没有被注册到Ioc容器中
三种方式我们平常开发一般常用的是@Service ,@Configuration + @Bean 这2种,其他的我们一般会在源码中看到。