一、背景
二、代码
2.1 第一种:@Component+@ConfigurationProperties(prefix = “myperson”)
bean文件
@Component
@ConfigurationProperties(prefix = "myperson")
@Data
@ToString
public class Person {
private String name;
private String age;
}
配置文件 application.properties
myperson.name="jim"
myperson.age=18
测试:
@Autowired
public Person person;
@Test
public void getPerson(){
System.out.println(“★★★★★★—》”+person.toString());
}
结果:
2.2 第二种:@Configuration+@EnableConfigurationProperties+@ConfigurationProperties(prefix = “myperson”)
bean,这种方式可应用与第三方的ben包,如果第三方的这个bean包只配置了@ConfigurationProperties(prefix = “myperson”) 而3没有配置 @Component的情况下试用
//@Component
@ConfigurationProperties(prefix = "myperson")
@Data
@ToString
public class Person {
private String name;
private String age;
}
配置类
// 配置类标识
@Configuration(proxyBeanMethods = false)
// 开启自动配置
@EnableConfigurationProperties(Person.class)
public class Animal{
}
三、2中方法可以引用这个bean
1)@Autowired 注解
@Autowired
public Person person;
@Test
public void getPerson(){
System.out.println("★★★★★★---》"+person.toString());
}
结果:
2)★通过有参构造器传参引入(如果只有一个有参构造器),有参构造器的参数默认是从容器中拿的。
测试: