动态注入属性值(一)

一、在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=shazima
test.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} "
          />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值