动态注入属性值(一)

来源:互联网 发布:淘宝主图设计技巧 编辑:程序博客网 时间:2024/06/06 03:59

一、在javaConfig中利用Environment注入属性值
1、普通的Student类

public class Student {    private int age;    private String name;    public Student(int age,String name){        this.age=age;        this.name=name;    }    public void display(){        System.out.println("name:"+name+"  age:"+age);    }}

2、属性值文件 testvalue.properties

test.name=shazimatest.age=3232

3、JavaConfig配置文件

import org.springaction.Student;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.core.env.Environment;@Configuration//声明属性源@PropertySource("classpath:testvalue.properties")public class StudentConfig {    //注入environment    @Autowired    Environment env;    @Bean    public Student student(){    //如果属性值key不存在,可以设置默认值,没有指定默认值,那获取值就是null;env.getProperty(String key[,String defaultValue])    //实际age类型是int,而获取的类型是String,需要进行转换env.getProperty(String key,Integer.class[,int defaultValue])    //获取的属性值必须要定义 env.getRequiredProperty()方法,如果没有定义则抛出异常        return new Student(env.getProperty("test.age",Integer.class),env.getProperty("test.name")){};    }}

4、测试文件

@RunWith(SpringJUnit4ClassRunner.class)//配置类@ContextConfiguration(classes = StudentConfig.class)public class CDPConfigTest {    @Autowired    private Student student;    @Test    public void doP(){        student.display();    }}

二、利用属性占位符注入属性值
1、在JavaConfig中使用占位符

@Configuration//声明属性源@PropertySource("classpath:testvalue.properties")public class StudentConfig {//它能够基于Spring Environment及其属性源来解析占位符    @Bean    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){        return new PropertySourcesPlaceholderConfigurer();    }    @Bean    public Student student(         @Value("${test.age}") int age,         @Value("${test.name}") String name)    {        return new Student(age,name);    }}

2、在XML中通过属性占位符注入属性值
2.1、在XML中增加如下配置

<context:property-placeholder location="testvalue.properties"/>    <bean id="student" class="org.springaction.Student"          c:name="${test.name}"          c:age="${test.age} "          />