在解释我的问题之前,这是我的(简化的)代码:
foo.bar.MyFile
public class MyFile extends MyFileAbstract {
@Value("${FILE_PATH}")
private String path;
[...]
public MyFile(final Date date, final String number, final List<MyElement> elements) {
this.date = date;
this.number = number;
this.elements = elements;
}
@Override
public String getPath() {
return path;
}
[...]
}
foo.bar.MyService
@Service
public class MyService {
[...]
public String createFolder(MyFileAbstract file) throws TechnicalException {
[...]
String path = file.getPath();
[...]
}
[...]
}
服务的呼唤
[...]
@Autowired
MyService service;
public void MyMethod() {
MyFile file = new MyFile();
service.createFolder(file);
[...]
}
[...]
我使用上下文 XML 来配置 Spring:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:property-placeholder
file-encoding="utf-8"
location="file:///[...]/MyProperties.properties" />
<context:annotation-config />
<context:component-scan base-package="foo.bar.classes" />
[...]
</beans>
问题是变量path
在 MyService
中在运行时均为空和 MyFile
实例化时的文件 MyFile
调用我的服务 MyService
.
我正在寻找注入(inject)我的属性(property)的解决方案 ${FILE_PATH}
里面MyFile
.
这里是我的环境:
- Apache Tomcat 7
- Java 8
- Spring 4.1.6.RELEASE
我已经看到带有 @Configurable bean 的 Spring AOP 可以解决这个问题,但我不想更改我的 Java 代理,因为我不想修改生产服务器上的配置。
而且我不知道如何在 MyFile
上使用@Service使用我的自定义构造函数。
欢迎任何想法。
最佳答案
您可以添加到您的 MyService
@Autowired
private Environment environment;
获取值
environment.getProperty("FILE_PATH");
之后您可以根据需要将其设置到文件中。
关于java - 如何在 Spring 非托管类上使用@Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43778290/