1、Environment
@Configurable
@PropertySource("classpath:/userinfo.properties") //这个属性文件会加载到Spring的Environment中
public class UserInfoConfig {
@Autowired
private Environment env;
@Bean
public UserInfo userInfo() {
return new UserInfo(env.getProperty("user.name1"), Integer.parseInt(env.getProperty("user.age")), env.getProperty("user.sex"));
}
}
2、占位符
@Configurable
public class UserInfoConfig {
@Value("${user.name1}")
private String name;
@Value("${user.age}")
private Integer age;
@Value("${user.sex}")
private String sex;
@Bean
public UserInfo userInfo() {
return new UserInfo(name, age, sex);
}
/* @Bean
public UserInfo userInfo(@Value("${user.name1}") String name, @Value("${user.age}") Integer age, @Value("${user.sex}") String sex) {
return new UserInfo(name, age, sex);
}*/
@Bean
public static PropertySourcesPlaceholderConfigurer placeholder() {
PropertySourcesPlaceholderConfigurer placeHolder = new PropertySourcesPlaceholderConfigurer();
placeHolder.setLocation(new FileSystemResource("D:\05-javadev\test20200609_2\src\main\resources\userinfo.properties"));
//placeHolder.setLocation(new ClassPathResource("classpath:/userinfo.properties"));
return placeHolder;
}
}
3、spel
public class Student {
@Value("#{userInfo.name}")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Bean
public Student student() {
Student student = new Student();
return student;
}