繁体   English   中英

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

[英]How to use Spring @Value annotation in class level variables

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

   @Value(server.environment)
   public String environment;

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

在这里,问题是 fileName 首先初始化,然后发生环境注入。 所以我总是得到 null-SomeFileName.xls。

无论如何要传达在春天初始化第一个@Value

因此,您可以使用@PostConstruct 文档

PostConstruct 注解用于需要在依赖注入完成后执行任何初始化的方法。

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

public class MyService {

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

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

}

另一种方法是使用@Autowired配置方法。 文档

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

...

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

例子:

public class MyService {

    private String propertyValue;

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

}

不同之处在于,使用第二种方法,您的 bean 没有额外的钩子,您可以在它自动装配时对其进行调整。

您可以使用 @Value 从属性文件中读取值,这听起来更像是您要实现的目标。

如果您在 xml 或 bean 配置方法中配置 PropertySourcesPlaceholderConfigurer,则 spring 将为您设置该值。

@Value("${server.env}")
private String serverEnv;

还有配置....

@Configuration
public class Cfg {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    final PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("/foo.properties"));
    return propertySourcesPlaceholderConfigurer;
    }
}

或 xml 方法

<context:property-placeholder location="classpath*:foo.properties"/>

您还可以使用纯驱逐 @PostConstruct :

@Value("${server.environment}")
public String environment;

@Value("#{${server.environment} + 'SomeFileName.xls'}")
public String fileName;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM