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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rubulai/article/details/80427579

属性赋值: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();
	}

}

猜你喜欢

转载自blog.csdn.net/rubulai/article/details/80427579