简体   繁体   English

Spring @Value 注解

[英]Spring @Value annotation

I'm Spring newbie and I'm wondering what are prerequisites/conditions of using @Value annotation in Spring?我是 Spring 新手,想知道在 Spring 中使用 @Value 注释的先决条件/条件是什么?

What I have for now is a Token class which has hardcoded secret key as a field.我现在拥有的是一个 Token 类,它具有硬编码的密钥作为字段。 What I'm trying to do is to move this secret key to config file to eliminate hardcoding but for some reason the following is not working.我想要做的是将此密钥移动到配置文件以消除硬编码,但由于某种原因,以下内容不起作用。

public class Token {
//...some code

    @Value("${my.secretKey}")
    private String key;

//...some code
}

Maybe there is any standard technique to solving this type of tasks.也许有任何标准技术可以解决此类任务。
Thanks for help!感谢帮助!

ps I have .properties file which contains my.secretKey=123 entry. ps 我有包含my.secretKey=123条目的.properties文件。

Injecting dependencies and values only works on objects that are managed by Spring - when you manually create an object using new , for example by doing new Token() , then Spring cannot process the object to inject dependencies and values.注入依赖项和值仅适用于由 Spring 管理的对象 - 当您使用new手动创建对象时,例如通过执行new Token() ,则 Spring 无法处理该对象以注入依赖项和值。

The Token object must be a Spring bean for this to work. Token对象必须是 Spring bean 才能工作。

To use @Value annotation your Spring version must be 3.0+要使用@Value注释,您的 Spring 版本必须是3.0+

You must register a static PropertySourcesPlaceholderConfigurer bean in either XML or annotation, so that Spring @Value know how to interpret ${}您必须在 XML 或注释中注册一个静态PropertySourcesPlaceholderConfigurer bean,以便 Spring @Value知道如何解释${}

For more information想要查询更多的信息

https://www.mkyong.com/spring3/spring-value-default-value/ https://www.mkyong.com/spring3/spring-value-default-value/

One mistake can also be in proper location of .properties file.一个错误也可能出现在.properties文件的正确位置。 Your .properties file location is very important.您的.properties文件位置非常重要。 Your xyz.properties file must be place in your project's src folder, like : src/xyz.properties After that,你的xyz.properties文件必须放在你项目的src文件夹中,比如: src/xyz.properties之后,
Load your properties file in the XML config file : File: applicationContext.xml Add the following lines:在 XML 配置文件中加载您的属性文件:文件: applicationContext.xml添加以下几行:

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

This code should appear just after the <context:component-scan .../> line in your xml config file.此代码应出现在 xml 配置文件中的<context:component-scan .../>行之后。 And now现在
Inject the properties values into your Token class, It should work now.将属性值注入您的Token类,它现在应该可以工作了。
Happy Coding.快乐编码。

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

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