0
点赞
收藏
分享

微信扫一扫

springboot读取自定义properties并注入到bean中

小猪肥 2022-04-08 阅读 57
java后端

在使用springboot项目时,可使用@value的方式直接读取application.properties中的文件,但有时我们需要配置自定义的properties,下面方法将在springboot启动时利用fileinputstream读取properties文件中的内容,并注入到bean中,@Configuration注解会在springboot启动时执行一次,代码如下:

package com.shanqis.parking.properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* 读取resource下的.properties文件,将文件中的内容封装到map中,注入到bean中方便依赖注入
*
* @author Administrator
*/

@Configuration
public class PropertiesClassLoader {

private Logger logger = LoggerFactory.getLogger(PropertiesClassLoader.class);

private Map<String, Object> versionProperties = new HashMap<>(16);

private void init(String name) {

try {
Properties properties = new Properties();

InputStream in = PropertiesClassLoader.class.getClassLoader().getResourceAsStream(name + ".properties");

properties.load(in);

logger.info("加载{}.properties参数", name);

for (String keyName : properties.stringPropertyNames()) {
String value = properties.getProperty(keyName);

if ("version".equals(name)) {
versionProperties.put(keyName, value);
}

logger.info("{}.properties---------key:{},value:{}", name, keyName, value);
}
logger.info("{}.properties参数加载完毕", name);
} catch (IOException ignored) {

}

}

@Bean(name = "versionProperties")
public Map<String, Object> commonMap() {
init("version");
return versionProperties;
}
}

springboot启动日志如下:

然后在controller层或者service层等可以这样使用

/**
* 读取common.properties文件
*/

@Autowired @Qualifier("commonMap")
protected Map<String, String> commonMap;
举报

相关推荐

0 条评论