gpt4 book ai didi

spring - 如何在类级变量中使用 Spring @Value 注解

转载 作者:IT老高 更新时间:2023-10-28 13:53:50 26 4
gpt4 key购买 nike

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

   @Value(server.environment)
public String environment;

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

这里的问题是先初始化文件名​​,然后进行环境注入(inject)。所以我总是得到 null-SomeFileName.xls。

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

最佳答案

因此,您可以使用 @PostConstruct。来自 documentation :

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

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

public class MyService {

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

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

}

另一种方法是使用 @Autowired 配置方法。来自 documentation :

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

...

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 没有额外的钩子(Hook),您可以在 Autowiring 时对其进行调整。

关于spring - 如何在类级变量中使用 Spring @Value 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25257237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com