Config.class
@Configuration
@PropertySource("book.properties") //声明属性源
public class Config {
@Autowired
Environment env;
@Bean
public Book book(){
return new Book(env.getProperty("book.id"),env.getProperty("book.name"));
}
}
Book.class
public class Book {
private String id;
private String name;
public void show(){
System.out.println("id: "+this.id+"name: "+this.name);
}
public Book(String id,String name) {
this.id = id;
this.name = name;
}
}
book.properties
book.id=001
book.name=Spring从零到放弃
Config.class
@Configuration
@ComponentScan
public class Config {
@Bean
public PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
}
Book.class
@Component
@PropertySource("book.properties")
public class Book {
private String id;
private String name;
public void show(){
System.out.println("id: "+this.id+"name: "+this.name);
}
public Book(@Value("${book.id}") String id,
@Value("${book.name}") String name) {
this.id = id;
this.name = name;
}
}
book.properties
book.id=001
book.name=Spring从零到放弃
注意点:1. @Value 注解可以用在声明的变量上或者有参构造方法中,但是如果用在声明的变量上,就不能有有参构造函数,因为 Spring 自动装载的时候会在默认的无参构造方法和声明的有参构造方法之间为难,因此抛出异常。
? 2. 为了使用属性占位符,必须配置 PropertySourcesPlaceholderConfigurer bean 或者 PropertyPlaceholderConfigurer bean。
? 3. Environment 和属性占位符二者存其一,因为 PropertySourcesPlaceholderConfigurer 是基于 Environment 的,两者同时存在会有一些问题。
SpEl 表达式拥有很多特性,包括:
使用方法见:https://www.jianshu.com/p/e0b50053b5d3
原文:https://www.cnblogs.com/miou/p/12261601.html