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

查看:154
本文介绍了如何在类级变量中使用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.

无论如何要传递来在春天初始化第一个@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方法或config方法标记为 通过Spring的依赖项注入工具自动连线.

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

...

Config方法可以具有任意名称和任意数量的参数. 这些参数中的每一个都将与中的匹配bean自动连线 弹簧容器. Bean属性设置器方法实际上只是一个 这种常规配置方法的特殊情况.这样的配置方法 不必公开.

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天全站免登陆