Spring的@Value始终为null

5

我在我的应用程序中使用Spring,有一个.properties文件定义了一些值。

在一个Java类中有一个字符串值:

@Value("${test}")
public String value;

重点是,如果我在bean定义中注入这个值:
<bean id="customClass" class="package.customClass.CustomClassImpl">
    <property name="value" value="${test}"></property>
</bean>

这段代码本来是可以正常工作的,但如果我使用@Value注解,那么总是返回null。这是为什么呢?

不过,我没有使用"new"实例化"customClass",而是通过context.getBean("customClass")获取它。

编辑:我已经在上下文中配置了属性占位符。

<bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:config.properties</value>
                <value>classpath:constants.properties</value>
            </list>
        </property>
    </bean>

提前感谢您。


XML示例中的属性名称为“test”,而您在注释中使用了名称“value”,请仔细检查属性名称。 - Vlad Bochenin
编辑了一下,我的源代码没问题。 - user9945564
展示一下customClass的代码。 - Sangam Belose
4个回答

8
记住,你的类需要像 @Component@Service 这样的注释来作为模板。

3

如果您正在创建Spring Boot应用程序,并且您的目标是通过(application).properties提供配置参数,则有一种方法可以在不需要显式@Value声明的情况下完成。

使用注释@ConfigurationProperties(“some.prefix”)创建YourClassProperties:

@ConfigurationProperties("my.example")
public class MyClassProperties {
    private String foo;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }
}

将定义的属性添加到(application).properties文件中:

my.example.foo=bar

在你的应用程序中,你可以自动装配所需的属性...
@Autowired
private MyClassProperties myClassProperties;

...并将它们用作您将使用其他属性的方式:

LOG.info("Value of the foo: {}", myClassProperties.getFoo());

2
解决方法是,在配置文件中启用注解配置:<context:annotation-config/>

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接