5. Spring IOC 常见注解

5. Spring IOC 常见注解

@Configuration
@Import(value = {H.class, K.class, TestImportSelector.class, TestBeanDefinitionRegister.class})
@ComponentScan(basePackages = {"com.gmr.test"})
@PropertySource(value = {"classpath:user.properties"}) //指定外部文件的位置
public class MainConfig {

    @Bean
    @Scope(value = "prototype")
    public A a(){
    	return new A();
    }
    
    @Bean
    public B b(){
    	return new B();
    }
    
    @Bean
    @Lazy
    public C c(){
    	return new C();
    }

    @Bean
    @Profile(value = "test")
    public Test test(){
    	return new Test();
    }
    
    //当容器中有Test的组件,那么TestA才会被实例化.
    @Bean
    @Conditional(value = TestCondition.class)
    public TestA testA(){
    	return new TestA();
    }
}
  • @Configuration

  • @Bean

  • @CompentScan

    • excludeFilters

    • includeFilters 需要把useDefaultFilters属性设置为false(true表 示扫描全部的)

      @ComponentScan(basePackages = {"com.gmr.test"},includeFilters = {
          @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})},useDefaultFilters = false)
      
    • @ComponentScan.Filter

      public enum FilterType {
          //注解形式 比如@Controller @Service @Repository @Compent
          ANNOTATION,
          //指定的类型
          ASSIGNABLE_TYPE,
          //aspectJ形式的
          ASPECTJ,
          //正则表达式的
          REGEX,
          //自定义的
          CUSTOM
      }
      
    • FilterType.CUSTOM 需要自定义实现TypeFilter

      public class TestFilterType implements TypeFilter {
          @Override
          public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
          //获取当前类的注解源信息
          AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
          //获取当前类的class的源信息
          ClassMetadata classMetadata = metadataReader.getClassMetadata();
          //获取当前类的资源信息
          Resource resource = metadataReader.getResource();
          if(classMetadata.getClassName().contains("test")) {
          	return true;
          }
          return false;
      }
      
  • @Scope

  • @Lazy

  • @Conditional 进行条件判断

    public class TestCondition implements Condition {
        /**
        *
        * @param context
        * @param metadata
        * @return
        */
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            //判断容器中是否有test的组件
            if(context.getBeanFactory().containsBean("test")) {
            	return true;
            }
            return false;
        }
    }
    
  • @Import

    • ImportSeletor 类实现组件的导入 (导入组件的id为全类名路径)

      public class TestImportSelector implements ImportSelector {
          //可以获取导入类的注解信息
          @Override
          public String[] selectImports(AnnotationMetadata importingClassMetadata) {
              return new String[]{"com.gmr.test.User"};
          }
      }
      
    • ImportBeanDefinitionRegister 导入组件 (可以指定bean的名称)

      public class TulingBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
          @Override
          public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
              //创建一个bean定义对象
              RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(User.class);
              //把bean定义对象导入到容器中
              registry.registerBeanDefinition("user",rootBeanDefinition);
          }
      }
      
  • FacotryBean

    public class UserFactoryBean implements FactoryBean<Car> {
        // 返回bean的对象
        @Override
        public User getObject() throws Exception {
        	return new User();
        }
        // 返回bean的类型
        @Override
        public Class<?> getObjectType() {
        	return User.class;
        }
        // 是否为单利
        @Override
        public boolean isSingleton() {
        	return true;
        }
    }
    
  • @PostConstruct 和 @PreDestory 是 JSR250 规范

    @Component
    public class Test {
        public Test() {
        }
        @PostConstruct
        public void init() {
        }
        @PreDestroy
        public void destory() {
        }
    }
    
  • @Value 和 PropertySource

    public class User {
        //通过普通的方式
        @Value("郭")
        private String firstName;
        
        //spel方式来赋值
        @Value("#{28-8}")
        private Integer age;
        
        //通过读取外部配置文件的值
        @Value("${user.lastName}")
        private String lastName;
        }
    }
    
  • @Autowired 和 @Qualifier、@Primary

  • @Resource JSR250规范

  • @Repository @Service

  • 使用底层组件 BeanNameAware、BeanFactoryAware、ApplicationTextAware

  • @Profile

    • -Dspring.profiles.active=test|dev|prod
    • AnnotationConfigApplicationContext -> getEnvironment().setActiveProfiles(“test”,“dev”);

你可能感兴趣的:(Spring,专题,spring)