【问题标题】:How to import properties file within shared jar in Spring?如何在 Spring 的共享 jar 中导入属性文件?
【发布时间】:2014-07-21 14:39:53
【问题描述】:

我想创建一个包含一些服务的共享项目 jar。这些服务应该使用属性文件。

理想情况下,我只是想稍后在将共享 jar 作为依赖项添加到其他项目时使用这些服务。我不想做任何进一步的配置,比如导入共享属性文件等等。

在共享 jar 中,我想使用 Spring 注入属性。但是我该怎么做呢?

项目-commons/src/main/java:

@Service
public class MyService {
    @Value("${property.value}") private String value;

    public String getValue() {
        return value;
    }
}

project-commons/src/main/resources/application.properties:

property.value=test

项目-web/src/main/java:

@Component
public class SoapService {
    @Autowired
    private MyService service;

    //should return "test"
    public String value() {
        return service.getValue();
    }
}

当我运行它时:

Illegal character in path at index 1: ${property.value}

所以,属性文件没有被解析。但是如何让spring在使用合适的服务时自动使用呢?

【问题讨论】:

  • 你有加载属性的配置吗?
  • 不,应该吗?在另一个项目中注入此服务时,我宁愿不必配置任何东西。
  • 是的,否则使用属性的模块将不知道它们应该被加载。想想应用程序上下文是如何工作的。

标签: java spring


【解决方案1】:

感谢 Hank Lapidez 的评论,添加以下语句解决了问题:

@Configuration
@PropertySource("classpath:appdefault.properties")
public CommonConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

【讨论】:

    【解决方案2】:

    你需要有一些变化:

        <context:property-placeholder location="classpath:my.properties" ignore-unresolvable="true"/>
    

    在您的应用程序上下文 xml 文件中,或 java 配置器中的等效文件中(请参阅@PropertySource("classpath:my.properties"))。这应该在依赖于共享库的属性文件的任何模块中重复。

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 2018-02-27
      • 2017-09-17
      • 2015-10-26
      • 2020-05-18
      • 1970-01-01
      • 2016-10-18
      • 2017-06-04
      相关资源
      最近更新 更多