如何在类级变量中使用 Spring @Value 注解 [英] How to use Spring @Value annotation in class level variables

查看:59
本文介绍了如何在类级变量中使用 Spring @Value 注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在类的实例变量中使用 @Value 注入的参数,并且可以在其所有子类中重用该变量.

I need to use injected parameter by @Value in instance variable of a class and can be reused that variable in all its child classes.

   @Value(server.environment)
   public String environment;

   public String fileName = environment + "SomeFileName.xls";

这里的问题是文件名先初始化,然后环境注入发生.所以我总是得到 null-SomeFileName.xls.

Here, the problem is fileName initializing first and then environment injection is happening. So I am getting always null-SomeFileName.xls.

总之要传达在spring中初始化第一个@Value.

Anyway to convey to initialize first @Value in spring.

推荐答案

因此您可以使用 @PostConstruct.来自文档:

You can use @PostConstruct therefore. From documentation:

PostConstruct 注解用在一个需要做的方法上在依赖注入完成后执行以执行任何初始化.

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.

@PostConstruct 允许您在设置属性后进行修改.一种解决方案是这样的:

@PostConstruct allows you to perform modification after properties were set. One solution would be something like this:

public class MyService {

    @Value("${myProperty}")
    private String propertyValue;

    @PostConstruct
    public void init() {
        this.propertyValue += "/SomeFileName.xls";
    }

}

另一种方法是使用 @Autowired 配置方法.来自 文档:

Another way would be using an @Autowired config-method. From documentation:

将构造函数、字段、setter 方法或配置方法标记为由 Spring 的依赖注入工具自动装配.

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.

...

配置方法可以有任意名称和任意数量的参数;这些参数中的每一个都将使用匹配的 bean 自动装配弹簧容器.Bean 属性 setter 方法实际上只是一个这种通用配置方法的特殊情况.这样的配置方法做不必公开.

Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Such config methods do not have to be public.

示例:

public class MyService {

    private String propertyValue;

    @Autowired
    public void initProperty(@Value("${myProperty}") String propertyValue) {
        this.propertyValue = propertyValue + "/SomeFileName.xls";
    }

}

不同之处在于,使用第二种方法时,您无需为 bean 添加额外的钩子,而是在它自动装配时对其进行调整.

The difference is that with the second approach you don't have an additional hook to your bean, you adapt it as it is being autowired.

这篇关于如何在类级变量中使用 Spring @Value 注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆