java - 如何在 Spring 非托管类上使用@Value

标签 java spring tomcat code-injection

在解释我的问题之前,这是我的(简化的)代码:

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>

问题是变量pathMyService 中在运行时均为空和 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/

相关文章:

java - 在 Java 中比较 2 个 x509 证书

java - Hibernate 可以自动识别实体类型吗?

java - Spring 4.x 未显示 Thymeleaf 错误

java - 尽管放置正确,但找不到 jSTL

java - Tomcat 7 + Jersey 2.0 错误

java - Java 中带有 try 的 finally 方法

Java - 接口(interface)实现中的方法名称冲突

spring - 在 Spring Jpa 数据中加入 3 个表

java - Spring 启动 : Conditional on database type

Hibernate c3p0和DBCP连接池机制