我有一个Web应用程序,它使用包含某种属性的外部配置文件,这些属性在加载应用程序上下文之前加载:
public class StartupListener
extends org.springframework.web.context.ContextLoaderListener {
@Override
public void contextInitialized(ServletContextEvent event) {
com.acme.app.Configuration configuration
= com.acme.app.Configuration.loadFromFile("C:/config.xml");
// String dbUser = configuration.getDatabaseConfig().getUser();
// String dbPassword = configuration.getDatabaseConfig().getPassword();
super.contextInitialized(event);
}
}
C:\ config.xml中:
<config xmlns="http://www.acme.com/app/config">
...
<databaseConfig>
<user>...</user>
<password>...</password>
</databaseConfig>
...
</config>
的web.xml:
<web-app ...>
...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
...
<listener>
<listener-class>com.acme.app.StartupListener</listener-class>
</listener>
...
</web-app>
的applicationContext.xml:
<beans ...>
...
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
...
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
...
</bean>
...
</beans>
我希望在${db.user}
和${db.password}
属性可用后立即将其推送到上下文中:
com.acme.app.Configuration configuration
= com.acme.app.Configuration.loadFromFile("C:/config.xml");
String dbUser = configuration.getDatabaseConfig().getUser();
String dbPassword = configuration.getDatabaseConfig().getPassword();
但我只知道两种方法:
1)再创建一个配置文件为.properties文件:
C:\ anotherConfig.properties:
db.user=...
db.password=...
的applicationContext.xml:
<beans ...>
...
<context:property-placeholder location="file:C:/anotherConfig.properties"/>
...
</beans>
2)或向系统属性添加属性:
System.setProperty("db.user",
configuration.getDatabaseConfig().getUser());
System.setProperty("db.password",
configuration.getDatabaseConfig().getPassword());
两者对我来说都很糟糕(特别是第一个)。
有没有办法让这更像春天?也许是这样的:
public class MyPropertiesProvider
implements org.springframework.foo.bar.PropertiesProvider {
@Override
public Properties getProperties() {
Properties properties = new Properties();
com.acme.app.Configuration configuration
= com.acme.app.Configuration.loadFromFile("C:/config.xml");
properties.setProperty("db.user",
configuration.getDatabaseConfig().getUser());
properties.setProperty("db.password",
configuration.getDatabaseConfig().getPassword());
return properties;
}
}
的applicationContext.xml:
<beans ...>
...
<context:property-placeholder-provider ref="myPropertiesProvider"/>
<bean id="myPropertiesProvider" class="com.acme.app.MyPropertiesProvider"/>
...
</beans>
答案 0 :(得分:0)
要帮助生成属性,配置,脚本等,请查看Maven Central上提供的此插件:https://github.com/sofdes/config-generation-maven-plugin