且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在类级变量中使用Spring @Value批注

更新时间:2023-01-16 08:45:26

因此,您可以使用@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.