spring注入相关注解

  本次主要整理四个注解 @ComponentScan、@Scope、@Conditional、@Import

1. @ComponentScan(value = "com.xiaoguo") 报扫描注解: 扫描该路径下的@controller @component @service 等等注解并将其交给spring容器管理。可以选择只扫描那些组件或是排除那些组件: includeFilters=Filter[]:指定只包含的组件
excludeFilters=Filter[]:指定需要排除的组件;

注解:

1 @ComponentScan(value = "com.xiaoguo.annotation", excludeFilters = {
2         @ComponentScan.Filter(type = FilterType.CUSTOM, classes = {MyTypeFilter.class})
3 })
View Code

自定义顾虑类:

 1 package com.xiaoguo.annotation.filter;
 2 
 3 import com.xiaoguo.annotation.beans.Car;
 4 import org.springframework.core.io.Resource;
 5 import org.springframework.core.type.AnnotationMetadata;
 6 import org.springframework.core.type.ClassMetadata;
 7 import org.springframework.core.type.classreading.MetadataReader;
 8 import org.springframework.core.type.classreading.MetadataReaderFactory;
 9 import org.springframework.core.type.filter.TypeFilter;
10 
11 import java.io.IOException;
12 
13 /**
14  * @author xiaoguo
15  * @date 2019-10-14 下午 9:11
16  */
17 public class MyTypeFilter implements TypeFilter {
18 
19 
20 
21     @Override
22     public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
23         //获取当前正在扫描的类的类信息
24         ClassMetadata classMetadata = metadataReader.getClassMetadata();
25         String className = classMetadata.getClassName();
26         Class forName = null;
27         try {
28             forName = Class.forName(className);
29             if (Car.class.isAssignableFrom(forName)) {
30                 // true就加载到IOC容器
31                 return true;
32             }
33         } catch (ClassNotFoundException e) {
34             e.printStackTrace();
35         }
36         return false;
37     }
38 }
View Code

 

你可能感兴趣的:(spring注入相关注解)