我想在我的项目中使用类型安全配置(HOCON 配置文件),这有助于轻松和有组织的应用程序配置。目前我使用的是普通的 Java 属性文件(application.properties),在大型项目中很难处理。
我的项目是 Spring MVC(不是 Spring Boot 项目)。有没有办法支持我的 Spring 环境(我被注入(inject)到我的服务中)由类型安全配置支持。这不应该破坏我现有的环境使用,如 @Value
注释、@Autowired Environment
等。
我怎样才能以最小的努力和对我的代码的更改来做到这一点。
这是我目前的解决方案:寻找有没有其他更好的方法
@Configuration
public class PropertyLoader{
private static Logger logger = LoggerFactory.getLogger(PropertyLoader.class);
@Bean
@Autowired
public static PropertySourcesPlaceholderConfigurer properties(Environment env) {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
Config conf = ConfigFactory.load();
conf.resolve();
TypesafePropertySource propertySource = new TypesafePropertySource("hoconSource", conf);
ConfigurableEnvironment environment = (StandardEnvironment)env;
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addLast(propertySource);
pspc.setPropertySources(propertySources);
return pspc;
}
}
class TypesafePropertySource extends PropertySource<Config>{
public TypesafePropertySource(String name, Config source) {
super(name, source);
}
@Override
public Object getProperty(String name) {
return this.getSource().getAnyRef(name);
}
}
最佳答案
我想我想出了一种比手动添加 PropertySource
到属性源更惯用的方法。创建一个 PropertySourceFactory
并使用 @PropertySource
首先,我们的 TypesafeConfigPropertySource
几乎与您的相同:
public class TypesafeConfigPropertySource extends PropertySource<Config> {
public TypesafeConfigPropertySource(String name, Config source) {
super(name, source);
}
@Override
public Object getProperty(String path) {
if (source.hasPath(path)) {
return source.getAnyRef(path);
}
return null;
}
}
接下来,我们创建一个返回该属性源的 PropertySource 工厂
public class TypesafePropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Config config = ConfigFactory.load(resource.getResource().getFilename()).resolve();
String safeName = name == null ? "typeSafe" : name;
return new TypesafeConfigPropertySource(safeName, config);
}
}
最后,在我们的配置文件中,我们可以像任何其他 PropertySource
一样引用属性源,而不必自己添加 PropertySource:
@Configuration
@PropertySource(factory=TypesafePropertySourceFactory.class, value="someconfig.conf")
public class PropertyLoader {
// Nothing needed here
}
关于java - 由 Typesafe Config 支持的 Spring 环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38803381/