0

我无法加载位于 jar (project.service.jar) 内的 db.properties,该文件由 war 文件 (project-web.war) 引用。输出战争在 WEB-INF/lib/project.service.jar 中有 jar。services jar 包含 Web 应用程序使用的服务和 dao 类。jar 也被使用 jar 中的一些服务的 rest war 使用。战争开始时,我无法加载位于服务 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;
}

服务.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 应用程序和报告应用程序是否正确?还是建议对所有服务、休息、报告类进行单一战争?

4

2 回答 2

0

AFAIK,spring 应用程序上下文仅使用一个PropertySourcesPlaceholderConfigurer. 由于@PropertySource(value = { "classpath:db.properties" })似乎没有填充环境,我只能看到另一种解决方案:明确地将其添加到位置列表中AppConfig.java

    props.setLocations(new Resource[] { new ClassPathResource(
        "application.properties"), new ClassPathResource("db.properties")});

但我必须承认,这与其说是一个干净的解决方案,不如说是一种解决方法。

编辑 :

但通常情况下,是DataSourceConfig.java由spring配置机器扫描的,@PropertySource(value = { "classpath:db.properties" })应该填充环境。

于 2014-08-12T08:56:13.833 回答
0

你需要在任何 jar 中指定类路径,试试这个:@PropertySource(value = { "classpath*:db.properties" })

于 2014-09-17T01:19:05.947 回答