我通读了有关外部配置的Spring Boot文档,并且看到它会自动加载src / main / resources / application.properties文件,然后可以使用注释将其连接到Bean属性。
但是我想有一个通用PropertyHelper
类,可用于使用java.util.Properties
application.properties中的属性来构建。能做到吗?
目前,我们正在手动实现此目标,如下所示:
public class PropertyHelper {
private static Properties loadProperties() {
try {
String propsName = "application.properties";
InputStream propsStream = PropertyHelper.class
.getClassLoader().getResourceAsStream(propsName);
if (propsStream == null) {
throw new IOException("Could not read config properties");
}
Properties props = new Properties();
props.load(propsStream);
您可以创建一个Wrapper
环境,将返回一个现成的使用环境PropertySource
:
您将以这种方式使用它:
@PropertySource(name="myName", value="classpath:/myName.properties")
public class YourService {
@Autowired
private CustomMapProperties customMapProperties;
...
MapPropertySource mapPropertySource = customMapProperties.getMapProperties("myName");
for(String key: mapPropertySource.getSource().keySet()){
System.out.println(mapPropertySource.getProperty(key));
}
CustomMapProperties
被注入Environment
并根据其名称返回请求和加载的属性文件:
@Component
public class CustomMapProperties {
@Autowired
private Environment env;
public MapPropertySource getMapProperties(String name) {
for (Iterator<?> it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext();) {
Object propertySource = it.next();
if (propertySource instanceof MapPropertySource
&& ((MapPropertySource) propertySource).getName().equals(name)) {
return (MapPropertySource) propertySource;
}
}
return null;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句