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])

阅读 6.4k
2 个回答

不需要 get set 方法

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

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

既然你要注入的是整个 properties,那么应该写的是:

@Value("#{propertiesReader}")
public void setProps(Properties props) {
    this.props = props;
}

而不是

@Value("#{propertiesReader[username]}")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题