@Value注解和@PropertySource 和@ImportResource 注解的使用说明
1、作用和说明
- @Value 相当于原来配置文件中的 value属性 <property name="age" value="20"/>
- @PropertySource 相当于原来配置文件中的 <context:property-placeholder location="classpath:/person.properties"></context:property-placeholder> 这个标签,把属性 会放到环境变量中 Environment,作用于.properties 文件
- @ImportResource 他针对的是我们自定义的.xml文件
2、代码说明
@Configuration @PropertySource(value = {"classpath:config/user.properties"}) @ImportResource(value={"classpath:config/bean.xml"}) public class MyUserConfig { @Bean public User getUser(){ return new User(); } } @RestController public class UserController { @Resource User user; @Resource PersonService personService; @GetMapping("/h2") public String test() { personService.print(); return user.getUsername(); } } public class User { @Value("${user.name2}") private String username; private int age; private String userId; public User() { } public User(String username, int age, String userId) { this.username = username; this.age = age; this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }