日志记录器做成@EnableLogger注解开启的功能之后,已经大大的简便了,但是当我定义很多@AppointLogger注解去指定方法时,会发现每一个注解都需要进行配置,所以需要将注解的配置集中一下
作用将每一个指定方法的注解@AppointLogger的配置做成可以由本项目的配置文件(yml、properties)进行统一配置
自定义第一步 定义一个配置类,用于映射配置
@Component //注入
@Data
@ConfigurationProperties(prefix = "appoint.logger") //定义在配置文件中的前缀以及表名配置映射类
public class LoggerProperties {
//属性就是yml文件中可配置的字段
private String loggingType;
private String loggingPath;
}
对应(如下图)
第二步 定义一个配置类,导入配置映射类 , 然后将本项目中所有的Bean全部返回实例并注入(包含配置映射类)
@EnableConfigurationProperties(LoggerProperties.class)//注入配置映射类
@Configuration
public class LoggerConfig {
@Bean
public LoggingAspects getLoggingAspects() {
return new LoggingAspects();
}
@Bean
public LogMapper getLogMapper() {
return new DefaultLogMapperImpl();
}
@Bean
public LoggingUtils getLoggingUtils() {
return new LoggingUtils();
}
@Bean
public SpringUtils getSpringUtils() {
return new SpringUtils();
}
}
第三步 在resources文件夹下面创建meta-INF文件夹,在meta-INF文件夹下面创建文件
spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.lian.song.idea.log.config.LoggerConfig org.springframework.boot.autoconfigure.EnableAutoConfiguration= 是固定写法 com.lian.song.idea.log.config.LoggerConfig 表示配置类所在的位置为什么
1 主程序的@SpringBootApplication注解中有@EnableAutoConfiguration注解,这个注解看名字就知道是用于自动配置的
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}
2 @EnableAutoConfiguration注解又导入了一个自动配置类,自动配置的工作主要由主动配置类完成,@EnableAutoConfiguration注解起到一个开启关闭的作用
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
@Inherited
@AutoConfigurationPackage
@import(AutoConfigurationimportSelector.class)
public @interface EnableAutoConfiguration {
}
3 AutoConfigurationimportSelector类最终实现了importSelector接口的selectimports()方法,这个方法返回类的全类名,并且返回全类名的类会被注入到IOC容器中
@Override
public String[] selectimports(Annotationmetadata annotationmetadata) {
if (!isEnabled(annotationmetadata)) {
return NO_importS;
}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationmetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
// getAutoConfigurationEntry()
4 那么这个方法去哪里寻找全类名呢?
protected AutoConfigurationEntry getAutoConfigurationEntry(Annotationmetadata annotationmetadata) {
if (!isEnabled(annotationmetadata)) {
return EMPTY_ENTRY;
}
AnnotationAttributes attributes = getAttributes(annotationmetadata);
List configurations = getCandidateConfigurations(annotationmetadata, attributes);
configurations = removeDuplicates(configurations);
Set exclusions = getExclusions(annotationmetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationimportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
// getCandidateConfigurations()
protected ListgetCandidateConfigurations(Annotationmetadata metadata, AnnotationAttributes attributes) { List configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in meta-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; } // Assert.notEmpty(configurations, "No auto configuration classes found in meta-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); 断言之前肯定需要先找到 // loadFactoryNames()
public static ListloadFactoryNames(Class> factoryType, @Nullable ClassLoader classLoader) { ClassLoader classLoaderToUse = classLoader; if (classLoader == null) { classLoaderToUse = SpringFactoriesLoader.class.getClassLoader(); } String factoryTypeName = factoryType.getName(); return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList()); } // loadSpringFactories()
private static Map> loadSpringFactories(ClassLoader classLoader) { Map > result = (Map)cache.get(classLoader); if (result != null) { return result; } else { HashMap result = new HashMap(); try { Enumeration urls = classLoader.getResources("meta-INF/spring.factories"); while(urls.hasMoreElements()) { URL url = (URL)urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); Iterator var6 = properties.entrySet().iterator(); while(var6.hasNext()) { Entry, ?> entry = (Entry)var6.next(); String factoryTypeName = ((String)entry.getKey()).trim(); String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue()); String[] var10 = factoryImplementationNames; int var11 = factoryImplementationNames.length; for(int var12 = 0; var12 < var11; ++var12) { String factoryImplementationName = var10[var12]; ((List)result.computeIfAbsent(factoryTypeName, (key) -> { return new ArrayList(); })).add(factoryImplementationName.trim()); } } } result.replaceAll((factoryType, implementations) -> { return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); }); cache.put(classLoader, result); return result; } catch (IOException var14) { throw new IllegalArgumentException("Unable to load factories from location [meta-INF/spring.factories]", var14); } } } // Enumeration urls = classLoader.getResources("meta-INF/spring.factories"); 表示每一个Jar包中的以及本项目的resources/meta-INF/spring.factories文件会被读取,会得到url(统一资源定位符)
所以我们配置的com.lian.song.idea.log.config.LoggerConfig路径会被读取出来
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.lian.song.idea.log.config.LoggerConfig
然后通过全类名注入Bean到IOC容器中
扩展
获取全类名之后还有这个方法getOrDefault()
(List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
yTypeName, Collections.emptyList());
```java
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
看接口的默认实现就知道,是确保不会重复读取默认配置的(spring.factories)



