配置文件相关
标签作用
@Component:将类注册到Bean
@ConfigurationProperties( prefix = "" ):用yml中的配置自动注入类
@Value(""):自动注入时的值或属性
@Autowired:启动自动注入
@PropertySource(value = "classpath:resource目录下文件"):加载指定配置文件
注入方式
@Value注解注入
Value注解注入时,既可以使用字面量,也可以用Spring表达式,还可以使用电脑配置。
@Component //注册bean到容器中
public class Dog {
@Value("哈士奇")
private String name;
@Value("2")
private Integer age;
//有参构造,无参构造,Get,Set,ToString()...
}
@Autowired
Dog dog;
@Component
@PropertySource(value = "classpath:user.properties")
public class User {
@Value("${user.name}") //电脑用户的名字
private String name;
@Value("#{9*2}") //Spring表达式
private int age;
@Value("男") //字面量
private String sex;
//有参构造,无参构造,Get,Set,ToString()...
}
user.properties配置文件
user1.name=Cai Xukun
user1.age=20
user1.sex=男
输出
![]()
yml注入
@Component //注册bean
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Cat cat;
//有参构造,无参构造,Get,Set,ToString()...
}
person:
name: Huang Jianbo
age: 3
birth: 1999/01/01
maps: {k1: v1,k2: v2}
lists:
- singing
- dancing
- rap
- music
- basketball
cat:
name: 伊丽莎白
age: 2
@Autowired
Person person;
会将person下的名字相同的注入,若名字不相同,则值为null
加载指定配置文件并注入
创建配置文件person.properties
name=Huang Jianbo
@Component //注册bean
@PropertySource(value = "classpath:person.properties") //从指定配置注入
public class Person {
@Value("${name}") //指定属性
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Cat cat;
//有参构造,无参构造,Get,Set,ToString()...
}
yml配置占位符
使用${内容}来配置
person:
name: Huang Jianbo${random.uuid}
age: ${random.int}
birth: 1999/01/01
maps: {k1: v1,k2: v2}
lists:
- singing
- dancing
- rap
- music
- basketball
cat:
name: ${person.hello:other}伊丽莎白
age: 2
happy: false
本文来自博客园,作者:Laplace蒜子,转载请注明原文链接:https://www.cnblogs.com/RedNoseBo/p/17160084.html

浙公网安备 33010602011771号