[英]Spring 4 - load property file inside the jar>war
我無法加載jar文件(project.service.jar)內的db.properties,該文件由war文件(project-web.war)引用。 輸出戰爭在WEB-INF / lib / project.service.jar中包含jar。 服務jar包含Web應用程序使用的服務和dao類。 其余戰爭中也使用了該jar,該戰爭使用了jar中的某些服務。 當戰爭開始時,我無法加載位於服務的jar文件中的db.properties。 該prop文件具有要在jndi中查找的數據源名稱。
戰爭配置
AppConfig.java
@Bean
public static PropertyPlaceholderConfigurer propertyConfigurer()
throws IOException {
PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
props.setLocations(new Resource[] { new ClassPathResource(
"application.properties") });
return props;
}
service.jar
@Component
@Configuration
//@ComponentScan(basePackages={ "com.mgage.mvoice" })
@PropertySource(value = { "classpath:db.properties" })
public class DatabaseConfig {
@Autowired
Environment environment;
private @Value(value = "${voice.datasource}") String dataSourceString;
@Bean
public DataSource getDataSource() {
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
try {
DataSource dataSource = lookup.getDataSource(dataSourceString); //this always is null
return dataSource;
} catch (DataSourceLookupFailureException e) {
return null;
}
}
@Bean
public PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
我應該嘗試將AppConfig.java導入DataSourceConfig.java導入,但是我仍然獲得Environment null。 我有什么想念的嗎? 將服務作為jar文件分開以使其可用於REST,Web應用程序和Reports應用程序是否正確? 還是建議對所有服務,休息和報告類別進行一次戰爭?
AFAIK,一種彈簧應用程序上下文,僅使用一個PropertySourcesPlaceholderConfigurer
。 由於@PropertySource(value = { "classpath:db.properties" })
似乎沒有填充環境,因此我只能看到另一種解決方案:將其顯式添加到AppConfig.java
中的位置列表中:
props.setLocations(new Resource[] { new ClassPathResource(
"application.properties"), new ClassPathResource("db.properties")});
但是我必須承認,這不僅僅是一個干凈的解決方案,而是更多的工作。
編輯:
但是通常,如果Spring配置機器掃描了DataSourceConfig.java
,則@PropertySource(value = { "classpath:db.properties" })
應該填充環境。
您需要在任何jar中指定類路徑,請嘗試以下方法:@PropertySource(value = {“” classpath *:db.properties“})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.