Spring @Value 注释总是评估为空? [英] Spring @Value annotation always evaluating as null?

查看:23
本文介绍了Spring @Value 注释总是评估为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个包含以下条目的简单属性文件:

So, I have a simple properties file with the following entries:

my.value=123
another.value=hello world

这个属性文件正在使用 PropertyPlaceHolderConfigurer 加载,它引用了上面的属性文件.

This properties file is being loaded using a PropertyPlaceHolderConfigurer, which references the properties file above.

我有以下类,我正在尝试将这些属性加载到其中:

I have the following class, for which I'm trying to load these properties in to like so:

public class Config
{
    @Value("${my.value}")
    private String mValue;

    @Value("${another.value}")
    private String mAnotherValue;

    // More below...
}

问题在于,mValuemAnotherValue 始终为空...但在我的控制器中,该值加载得很好.什么给?

The problem is that, mValue and mAnotherValue are ALWAYS null... yet in my Controllers, the value is being loaded just fine. What gives?

推荐答案

如果 Config 的实例是通过 new 手动实例化的,那么 Spring 不会参与进来,因此注释将被忽略.

If instances of Config are being instantiated manually via new, then Spring isn't getting involved, and so the annotations will be ignored.

如果您无法更改代码以使 Spring 实例化 bean(可能使用 prototype 范围的 bean),那么另一种选择是使用 Spring 的加载时类加载器编织功能(请参阅文档).这是一些低级的 AOP,它允许您像往常一样实例化对象,但 Spring 会将它们传递到应用程序上下文中,以使它们连接、配置、初始化等.

If you can't change your code to make Spring instantiate the bean (maybe using a prototype-scoped bean), then the other option is to use Spring's load-time classloader weaving functionality (see docs). This is some low-level AOP which allows you to instantiate objects as you normally would, but Spring will pass them through the application context to get them wired up, configured, initialized, etc.

不过,它并不适用于所有平台,因此请阅读上面的文档链接,看看它是否适合您.

It doesn't work on all platforms, though, so read the above documentation link to see if it'll work for you.

这篇关于Spring @Value 注释总是评估为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆