@PropertySource
public class Person {
//通过普通的方式
@Value("person.username")
private String firstName;
//spel方式来赋值
@Value("#{28-8}")
private Integer age;
通过读取外部配置文件的值
@Value("${person.lastName}")
private String lastName;
}
@Configuration
@PropertySource(value={"classpath:person.properties"}) //指定外部文件的位置
public class MainConfig {
@Bean
public Person person() {
return new Person();
}
}
@ConfigurationProperties(prefix="",ignoreUnknownFields=true,ignoreInvalidFields=true)
ignoreUnknownFields:忽略未知的字段。
ignoreInvalidFields:是否忽略验证失败的字段。比如我们在配置文件中配置了一个字符串类型的变量,类中的字段是int类型,那肯定会报错的。如果出现这种情况我们可以容忍,则需要配置该属性值为true。该参数值默认为false
@ConfigurationProperties 能够批量注入配置文件的属性。而且支持 JSR 303 校验
@Value 只能一个个指定。
application.properties
com.example.demo.name=${aaa:hi}
com.example.demo.age=11
com.example.demo.address[0]=北京
com.example.demo.address[1]=上海
com.example.demo.address[2]=广州
com.example.demo.phone.number=1111111
@Component
@ConfigurationProperties(prefix = "com.example.demo")
public class People {
private String name;
private Integer age;
private List<String> address;
private Phone phone;
}
// 引用
@Autowired
People people
网友评论