组件注册
总结:
- 包扫描+组件标注注解(@Controller/@Service/@Repository/@Component)
- @Bean 导入第三包里面的组件
- @Import 快速给容器中导入一个组件 见第9点
- 使用spring提供的FactoryBean 见第10点
-
@Configuration 告诉spring这是一个配置类(等于配置文件)
-
@Bean 相当于xml的标签,给容器注册一个bean,id默认是用方法名作为id 也可以是用@Bean(“xxx”)的方式指定id
-
在配置类上是用 @ComponentScan(value = “com.xxx”) 指定扫描的包
-
//排除扫描哪些类 @ComponentScan(value = "com",excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class}) }) //扫描哪些类 @ComponentScan(value = "com",useDefaultFilters=false, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})} ) //指定多个扫描规则 @ComponentScans(value = { @ComponentScan(value = "com",useDefaultFilters=false, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})} ) })
-
FilterType ANNOTATION:按照注解, ASSIGNABLE_TYPE : 按照给定类型, ASPECTJ : 使用ASPECTJ表达式 CUSTOM 自定义规则 /
工程中没用过跳过.
-
@Scope prototype : 多实例的,每次获取的时候才会调用方法 singleton :单实例的,容器创建时才会创建
-
@Lazy 容器启动不创建对象,第一次使用bean时,才加载
-
@Conditional 按照一定条件进行判断.满足条件条件给容器注册bean
//1.自定义类实现Conditon接口 public class WindowsConditon implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { //获取当前环境 Environment environment = conditionContext.getEnvironment(); String property = environment.getProperty("os.name"); if (property.contains("Windows")){ return true; } return false; } } //2.注解 @Conditional({WindowsConditon.class}) @Bean public Son son1(){ Son son = new Son(); son.setName("windows"); return son; }
-
- @Import(xxx.class) 快速将类注册成bean ,也可添加下面两个接口的实现类.
- ImportSelector 返回需要导入的组件的全类名的数组.
- ImportBeanDefinitionRegistrar 自定义类实现该接口
-
自定义类MyFactoryBean实现FactoryBean接口
- getObject() 返回所需要的实例 当通过spring获取myFactoryBean时,实际上获得的是该方法返回的对象.如果想要获取该工厂bean的实例则需用"&myFactoryBean"
- getObjectType() 返回实例的class对象
- isSingleton() 是否单例