当前,我的应用程序加载了一个属性文件,该文件具有以逗号分隔的不同属性,
property=propertyA,propertyB,propertyC
我有一个代码,可以加载属性文件并将其分配为以下应用程序属性:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private String[] properties;
private PropertySource propertySource;
public WebAppInitializer() {
propertySource = getPropertySource();
String propertyStr = (String) propertySource.getProperty("property");
List<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().split(propertyStr));
properties = list.toArray(new String[list.size()]);
}
}
// @Override
public void onStartup(ServletContext ctx) throws ServletException {
super.onStartup(ctx);
}
protected WebApplicationContext createRootAppContext() {
Class[] configClasses = this.getRootConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
MyPropertySource.addToEnvironment(rootAppContext.getEnvironment());
rootAppContext.getEnvironment().getPropertySources().addFirst(propertySource);
rootAppContext.getEnvironment().setActiveProfiles(properties);
rootAppContext.register(configClasses);
return rootAppContext;
} else {
return null;
}
}
protected WebApplicationContext createServletAppContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
servletAppContext.getEnvironment().setActiveProfiles(properties);
Class[] configClasses = this.getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
}
}
现在,我们正在将这些属性迁移到Db,并希望从数据库中加载。我最初认为是添加以下代码:
@Autowired
PropertyRepository propertyRepository;
public WebAppInitializer() {
List<String> listDB = propertyRepository.getProperties();
if(listDB.isEmpty()) {
propertySource = getPropertySource();
String propertyStr = (String) propertySource.getProperty("property");
List<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().split(propertyStr));
properties = list.toArray(new String[list.size()]);
}
}
//Other pieces of code
}
但是,PropertyRepository始终为null。我想Spring尚未初始化应用程序。我在这里想念什么吗?还是我应该遵循其他方式?我必须在此阶段加载属性,因为我有基于这些属性初始化的不同功能。