Spring注解驱动开发——给bean的属性复制

属性赋值:Bean的属性上使用@Value注解:必须是由容器调用构造器创建的bean这些@Value中的属性值才会被注入,自己显示写了new方法的@Value属性就不起作用了,因为自己写了new方法则实例不是由容器创建

public class Person {

	@Value("张三丰")
	private String name;
	@Value("#{20-2}")
	private Integer age;
	@Value("${property.address}")
	private String address;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}

可以通过@Value注入基本数据类型、字符串、SpEL表达式(#{})、也可获取运行环境变量(${}),即properties文件中的变量值,在之前采用配置的方式的时候,需要使用<context:property-placeholder location="classpath:config.properties">标签指明配置文件的位置,在容器启动的时候会将这些文件中的键值对存储在运行环境中,使用注解的方式则需要在容器Bean上使用@PropertySource,@PropertySource的value属性是一个数组,可以同时指定多个配置文件,可以使类路径下的(classpath:),也可以是文件路径下的(file:)

@Configuration
@PropertySource("classpath:config.properties")
public class MainConfig {

	@Bean
	public Person person() {
		return new Person();
	}
}

配置文件中的值也可以通过applicationContext来获取:因为容器加载时会将这些配置的键值对存放在环境变量中

public class MainTest {

	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);

	@Test
	public void test1() throws Exception {
		ConfigurableEnvironment environment = context.getEnvironment();
		String property = environment.getProperty("property.address");
		System.out.println(property);
		context.close();
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值