我只是在一個稍微不同的方式解決類似的問題。我們的客戶希望配置數據庫連接細節,集成服務器位置和端口等,而無需重建戰爭。使用環境屬性來指向包含信息的外部文件可能會也可能不會,但它感覺有點骯髒。無論如何,這是一個稍微更企業的方式。
對於數據庫連接,我們使用JNDI查找,下面是集成服務器參數化的當前解決方案。參數可以來自至少三個不同的來源:
- 屬性文件,它可以用Maven配置文件覆蓋,並且需要在彈簧配置中可以訪問單行xml。這顯然是在戰爭文件裏面。
- web.xml上下文參數。當然,這也是在戰爭檔案中。
- Tomcat服務器可以用context.xml覆蓋init參數,這可以在戰爭之外。這恰好是定義JNDI上下文的文件,這很好。
下面是配置accessor bean的實現。它可以運行在servlet上下文中,也可以不運行(對於某些單元測試,啓動一個完整的Web服務器沒什麼意義,但我們仍然需要滿足spring bean注入)。
我並不是說這是一個完美的解決方案,但它是一個。沒有找到像谷歌這樣的事情。
@Service
public class IntegrationConfigurationImpl implements
IntegrationConfiguration, InitializingBean,
ServletContextAware, ApplicationContextAware {
private static final String SERVER_HOST_PROPERTY = "integration.server.host";
private static final String SERVER_PORT_PROPERTY = "integration.server.port";
private static final String PROPERTY_BEAN_NAME = "integrationProperties";
private ServletContext servletContext;
private ApplicationContext applicationContext;
private static final Logger log = LoggerFactory.getLogger(IntegrationConfigurationImpl.class);
private String serverHost = "foo";
private int serverPort = 42;
@Override
public String getServerHost() {
return serverHost;
}
@Override
public int getServerPort() {
return serverPort;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
// konfiguraation validointi..
if (servletContext == null) {
log.info("servlet context not set, not running as a web application. Trying to get properties from application context");
if (applicationContext.containsBean(PROPERTY_BEAN_NAME)) {
Properties p = (Properties)applicationContext.getBean(PROPERTY_BEAN_NAME);
serverHost = p.getProperty(SERVER_HOST_PROPERTY);
serverPort = Integer.valueOf(p.getProperty(SERVER_PORT_PROPERTY)).intValue();
} else {
log.info("Property bean not found :" + PROPERTY_BEAN_NAME);
}
} else {
serverHost = servletContext.getInitParameter(SERVER_HOST_PROPERTY);
serverPort = Integer.valueOf(servletContext.getInitParameter(SERVER_PORT_PROPERTY)).intValue();
}
log.info("Using integration server " + getServerHost() + ", port " + getServerPort());
}
}
向回答者:請注意,該鏈接的問題指出屬性必須是不重建WAR修改。否則'''確實是一個非常明顯的選擇。 –
BalusC
2011-05-25 11:06:13
@BalusC。所以,這是一個好的選擇?只是問,因爲它總是對我來說似乎是一個黑客。但有時如果它起作用,它就會起作用。 – 2011-05-25 11:25:29
這感覺可能是骯髒的,但除了把它放在類路徑中真的沒有更好的方法,如果需要解除WAR,只要你想改變外部配置文件的位置(不是我所知道的,已經回答了它:))。 – BalusC 2011-05-25 11:27:50