由类型安全配置支持的弹簧环境
2022-09-02 10:16:33
我想在我的项目中使用typeafe配置(HOCON配置文件),这有助于轻松和有组织的应用程序配置。目前我正在使用普通的Java属性文件(application.properties),这在大项目上很难处理。
我的项目是Spring MVC(不是Spring Boot项目)。有没有办法支持我的Spring环境(我正在注入到我的服务中)由typeafe配置支持。这不应该阻止我现有的环境用法,如注释等。@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);
}
}