Spring 在 Pojo / 对象上@Value 的可能性

Pat*_*Pat 4 java spring-annotations

关于 spring 注释 @Value 的小问题。

该注释功能强大、众所周知,并且提供了开箱即用的可能性,可以通过配置绑定布尔值、字符串等类型,甚至更复杂的数据结构(例如列表、Map<String, Integer>)。

    @Value("${my.string}")
    private String               myString;

    @Value("${my.flag}")
    private Boolean               someFlag;

 @Value("#{'${my.list.of.strings}'.split(',')}")
    private List<String>         myListOfStrings;

    @Value("#{${my.hashmap}}")
private Map<String, Integer> myHashMap;

Run Code Online (Sandbox Code Playgroud)
application.properties
my.string=something
my.flag=true
my.list.of.strings=hello,world
my.hashmap={'hello':'world','aaa':'bbb','ccc':'ddd'}
Run Code Online (Sandbox Code Playgroud)

问题:是否可以在我定义的某些 POJO 上使用 @Value? 就像是:

  @Value("${my.pojo}")
    private MyPojo myPojo;

public class MyPojo {
    
    private String firstName;
    private String lastName;
    private int age;
    private boolean isMarried;
    
}

application.properties
my.pojo={ "firstname": "john", "lastname": "doe", "isMarried": false, "age": 20 }
Run Code Online (Sandbox Code Playgroud)

并让@Value(或者其他东西)拾取它。我在上面尝试过,但没有得到 myPojo。请问有什么解决方案可以在 @Value 下配置此功能?

谢谢

Nic*_*ach 9

Spring 无法将这些值注入到 POJO 中,因为根据定义,POJO 不由 Spring 的 IoC 容器管理。

\n

如果您查看 @Value 注释的 Spring 文档(链接在底部),它指定“请注意,@Value 注释的实际处理是由 BeanPostProcessor 执行的”,这本身就非常明确,即类必须是 Spring bean,但如果上下文还不够,请查看 BeanPostProcessor 文档(也在底部链接):“例如,允许自定义修改新 bean 实例 \xe2\x80\x94 的工厂钩子,检查标记接口或用代理包装 bean”

\n

所以不,如果该类不是由 Spring 的 IoC 容器管理(即,如果该类不是 Spring bean),则值注释将不会被 BeanPostProcessor 捕获,因此不会有用。

\n

值注释文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html

\n

BeanPostProcessor 文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html

\n

如果绝对必要,您始终可以使用 jdk-native 类从属性文件中读取值(快速示例: https: //www.javatpoint.com/properties-class-in-java

\n

根据记录,POJO 的规范意味着该类不能包含预先指定的注释。因此,即使在 @Value 可以在非 spring bean 上工作的另一个世界中,根据定义,它仍然会破坏类的 POJO 方面。

\n