Spring4 根据类型自动装配属性类型为java.util.Properties

查看:210
本文介绍了Spring4 根据类型自动装配属性类型为java.util.Properties的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

1.配置文件:

<bean id="person4" class=".." autowire="byType" />

<util:properties id="propertiesReader" location="classpath:yuan.properties" /> 


2.相关代码

    public class Person{
        private Properties props;
    
        @Value("#{propertiesReader[username}")
        public void setProps(Properties props) {
            this.props = props;
        }
        //..
    }


3.尝试解决的方案:

1.<util:properties id="propertiesReader" location="classpath:test.properties" />

2、在类中需要注入的属性实现 setter 和 getter 方法。

3、在 setter 方法前,添加 @Value 注解

@Value ("#{propertiesReader[propertiesName]}")

propertiesName 为 properties 文件中的键。这样,在容器启动过程中, Spring 将自动注入值。


4.异常信息(说找到2个.properties 文件):org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person4' defined in class path resource [beans.xml]: Unsatisfied dependency expressed through bean property 'props': : No qualifying bean of type [java.util.Properties] is defined: expected single matching bean but found 2: propertiesReader,systemProperties; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [java.util.Properties] is defined: expected single matching bean but found 2: propertiesReader,systemProperties


5.控制台:

信息: Loading properties file from class path resource [yuan.properties](从类路径资源加载属性文件[yuan.properties])


解决方案

不需要 get set 方法

@Value("#{propertiesReader}")
public Properties props;

@Value("#{propertiesReader['username']}")
public String username;

这篇关于Spring4 根据类型自动装配属性类型为java.util.Properties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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