欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot读取自定义的配置文件

程序员文章站 2022-05-01 23:04:54
...

比如我在项目中的resources目录下新建了一个mysql.properties文件此时需要读取当前文件怎么办???

可以使用@PropertySource(value="classpath:/mysql.properties")配合@Configuration 进行配置,通过Environment读取

/**
 *
 * @author youshang
 * @date 2021/02/26 16:29
 **/
@PropertySource(value = "classpath:/mysql.properties")
@Configuration
public class MyConfig4 {

    @Autowired
    Environment environment;

    @PostConstruct
    public void prere(){
        String property = environment.getProperty("server.port");
        System.out.println(property);
    }
}

源码解读

通过ConfigurationClassPostProcessor这个类去解析的,如果想看详细的欢迎去看我另外一篇博客讲解ConfigurationClassPostProcessor

在被执行第二步的时候开始解析@PropertySource(第一步是@Component注解)

private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
	String name = propertySource.getString("name");
	if (!StringUtils.hasLength(name)) {
		name = null;
	}
	String encoding = propertySource.getString("encoding");
	if (!StringUtils.hasLength(encoding)) {
		encoding = null;
	}
	String[] locations = propertySource.getStringArray("value");
	Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
	boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");
	Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
	PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
			DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));
	for (String location : locations) {
		try {
			//解析占位符
			String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
			//获取配置文件数据
			Resource resource = this.resourceLoader.getResource(resolvedLocation);
			//添加进Spring 环境(Environment)
			addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
		}
		catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
			// Placeholders not resolvable or resource not found when trying to open it
			if (ignoreResourceNotFound) {
				if (logger.isInfoEnabled()) {
					logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
				}
			}
			else {
				throw ex;
			}
		}
	}
}


/**
 * 将解析的配置文件添加进上下文环境 重点可以关注这个接口 ConfigurableEnvironment
 */
private void addPropertySource(PropertySource<?> propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
	if (this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		if (existing != null) {
			PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
					((ResourcePropertySource) propertySource).withResourceName() : propertySource);
			if (existing instanceof CompositePropertySource) {
				((CompositePropertySource) existing).addFirstPropertySource(newSource);
			}
			else {
				if (existing instanceof ResourcePropertySource) {
					existing = ((ResourcePropertySource) existing).withResourceName();
				}
				CompositePropertySource composite = new CompositePropertySource(name);
				composite.addPropertySource(newSource);
				composite.addPropertySource(existing);
				propertySources.replace(name, composite);
			}
			return;
		}
	}

	if (this.propertySourceNames.isEmpty()) {
		//添加进上下文
		propertySources.addLast(propertySource);
	}
	else {
		String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
		propertySources.addBefore(firstProcessed, propertySource);
	}
	this.propertySourceNames.add(name);
}