【发布时间】:2017-03-01 05:42:26
【问题描述】:
我们有一个 Spring 托管应用程序,它使用另一个 jar 作为依赖项,其中包含一个 Spring 托管服务类,需要使用从属性文件注入的一些值
带有 Spring 上下文设置的主应用程序
public static void main(String[] args) {
GenericXmlApplicationContext appContext = new GenericXmlApplicationContext("applicationContext.xml");
SomeClass someClass = (SomeClass) appContext.getBean("someClass");
someClass.someMethod();
...
从依赖jar调用服务的类
public class SomeClass {
private ServiceFromTheOtherJar serviceFromTheOtherJar;
public SomeClass(ServiceFromTheOtherJar serviceFromTheOtherJar) {
this.serviceFromTheOtherJar = serviceFromTheOtherJar;
}
public void someMethod() {
serviceFromTheOtherJar.call();
...
主应用的applicationContext.xml
<bean name="serviceFromTheOtherJar" class="com...ServiceFromTheOtherJar"/>
<bean name="someClass" class="com...SomeClass">
<constructor-arg ref="serviceFromTheOtherJar"/>
</bean>
依赖jar中的服务类
public class ServiceFromTheOtherJar {
private String someFieldWeWantToFillFromPropertyFile;
public void setSomeFieldWeWantToFillFromPropertyFile(String someFieldWeWantToFillFromPropertyFile) {
this.someFieldWeWantToFillFromPropertyFile = someFieldWeWantToFillFromPropertyFile;
}
public void call() {
//we would like to use the filled someFieldWeWantToFillFromPropertyFile here
...
当然,我们在依赖 jar 中有一个 application.properties 文件,其中包含我们想要注入 someFieldWeWantToFillFromPropertyFile 的属性值
现在我们可以将依赖 jar 作为依赖添加到主应用程序;当主应用程序正在执行时,它的 Spring 上下文设置得很好,并且 ServiceFromTheOtherJar.call() 方法被按预期调用;但是 someFieldWeWantToFillFromPropertyFile 并没有从属性文件中得到填充,无论我们到目前为止尝试过什么(例如@PropertySource({"application.properties"})、Environment.getProperty(...) 等)
限制
我们在两个 jar 中都有 Spring 3 版本,由于部署环境的原因,它必须保持不变;所以 Spring 4 解决方案是没有问题的
正如您在上面看到的,主应用程序当前使用 GenericXmlApplicationContext 并且更改似乎表明对应用程序进行了重大重写。因此,例如似乎无法在 ServiceFromTheOtherJar 上使用 @Service 注释,因为它在执行和上下文设置期间导致 BeanCreationException
【问题讨论】:
标签: java xml spring properties applicationcontext