spring注解驱动开发(五):Bean属性赋值
属性赋值,配置文件默认加到环境变量中,使用@Value给变量赋值
代码示例:
1.定义person类
public class Person { @Value("张三") private String username; @Value("${person.age}") private Integer age; public Person() { } public Person(String username, Integer age) { this.username = username; this.age = age; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Person{" + "username='" + username + '\'' + ", age=" + age + '}'; } }
2.定义配置文件 person.properties
person.name=李四
person.age=19
3.定义配置类
/** * @Value("字符串、数字、boolean、#{spel},${spring配置文件}") */ @Configuration @PropertySource("classpath:/org/gwsix/ch05/person.properties") public class MainConfig05 { @Bean public Person person(){ return new Person(); } }
4.添加测试类和测试方法
public class Main { @Test public void testProperties(){ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig05.class); System.out.println(applicationContext.getBean("person")); String property = applicationContext.getEnvironment().getProperty("person.name"); System.out.println(property); } }
5.控制台打印bean及从环境变量获得值
Person{username='张三', age=19}
李四
小结:@Value可以采用读取配置文件方式,配置文件会放到环境变量中,可以使用getProperty来取得配置文件中的值。
作者:
i孤独行者
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号