使用 Spring & 注入属性注释@Value [英] Injecting Properties using Spring & annotation @Value

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

问题描述

我正在尝试将一个属性文件加载到 Spring bean 中,然后将该 bean 注入到一个类中.

我无法开始工作的唯一部分似乎是使用了@Resource 引用.有人可以帮我连接最后一部分吗?我每次都得到一个空值.好像不想注入值.

- 我最初认为使用 @Resource 是最好的方法,但我发现建议的解决方案更容易.

我在另一篇文章中看到了这个解决方案:

参考解决方案链接: 前几章,因为 a) 很好读 b) 如果基础知识清晰,您会发现理解 Spring 会容易得多.

I am trying to load a properties file into a Spring bean and then inject that bean into a class.

The only part I can't get to work seems to be using the @Resource reference.Can someone connect the last piece for me? I get a null value every time. Doesn't seem to want to inject the value.

[EDIT] - I originally thought using the @Resource was the best way but the proposed solution I found easier.

I saw this solution in another post:

Reference Solution Link: Inject Property Value into Spring - posted by DON

Credit to Don for the post but I just wasn't sure how to finish it with the @Resource.

Debugging Results: The variable value appProperties is always null. It's not being injected.

Spring Config.

Sample Class:

package test;

import java.util.Properties;
import javax.annotation.Resource;


public class foo {
    public foo() {}
    @Resource private java.util.Properties appProperties;
}

Based on the advice in the approved solution below. Here are the changes I made.


Solution Update:

Spring Config:

Java Class:

解决方案

For your solution to work you would also need to make foo a Spring managed bean; because otherwise how would Spring know that it has to deal with any of your annotations on your class?

  • You can either specify it in your appcontext xml as a bean with ..class="foo"
  • Or use component-scan and specify a base package which contains your foo class.

Since I'm not entirely sure this is exactly what you want (don't you want a .properties file to be parsed by Spring and have it's key-value pairs available instead of a Properties object?), I'm suggesting you another solution: Using the util namespace

<util:properties id="props" location="classpath:com/foo/bar/props.properties"/>

And reference the values inside your beans (also, have to be Spring managed):

@Value("#{props.foo}")
public void setFoo(String foo) {
    this.foo = foo;
}

EDIT:

just realized that you are importing org.springframework.context.ApplicationContext in your class which is probably unnecessary. I strongly encourage you to read Spring reference at least the first few chapters, because a) it's a great read b) you will find it much easier to understand Spring if the basics are clear.

这篇关于使用 Spring &amp; 注入属性注释@Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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