我希望在我的项目中使用类型安全的配置(HOCON配置文件),以便轻松有序地进行应用程序配置。目前我正在使用普通的Java属性文件(application.properties),在大型项目中难以处理。
我的项目是Spring MVC(不是Spring Boot项目)。有没有办法将我的Spring Environment(我正在向服务注入的Environment)备份为类型安全的配置,而不会破坏我现有的Environment使用,如@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);
}
}
ApplicationContextInitializer
添加属性源是更好的解决方案,尝试像你目前做的那样硬塞进去并不是最好的解决办法。 - M. Deinum