最终属性@Value 中的 Spring 属性注入 - Java [英] Spring Property Injection in a final attribute @Value - Java

查看:23
本文介绍了最终属性@Value 中的 Spring 属性注入 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于从属性文件为最终属性注入 Spring 的一个简单问题.

A simple question on Spring injection from a properties file for a final attribute.

我有一个属性文件,我想在其中存储文件路径.通常,当我使用属性文件时,我会使用以下内容设置类属性:

I have a properties file which I want to store a file path in. Generally when I use properties files I setup class attributes using something like this:

private @Value("#{someProps['prop.field']}") String someAttrib ;

然后在我的 spring.xml 中我会有类似的东西:

Then in my spring.xml I would have something like:

<util:properties id="someProps"   
    location="classpath:/META-INF/properties/somePropFile.properties" />

这很好用,很简单,使代码漂亮整洁.但我不确定在尝试将属性值注入最终类属性时使用的最简洁模式是什么?

This works well, is simple and makes code nice and neat. But I'm not sure what is the neatest pattern to use when trying to inject properties values into final class attributes?

显然类似于:

private static final @Value("#{fileProps['dict.english']}") String DICT_PATH; 

不会工作.还有别的办法吗?

will not work. Is there another way?

推荐答案

将值注入最终字段的唯一方法是通过 构造函数注入.对 Spring 而言,其他一切都将是一个可怕的黑客.

The only way you can inject values into a final field is through Constructor Injection. Everything else would be an awful hack on Spring's side.

这篇关于最终属性@Value 中的 Spring 属性注入 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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