SpringBoot引入配置文件属性自定义为Bean

  1. 在配置文件中写入配置属性
wll.test.name=vsalw wll.test.age=888
  1. 自定义一个实体类
//@Component @Data @ConfigurationProperties(prefix = "wll.test")//前缀 public class Userproperties { private String name; private Integer age; }
 
  1. 自定义配置类来配置实体类
@Configuration @EnableConfigurationProperties(EmqConnectProperties.class) @ConditionalOnProperty(prefix = "emq.connect", name = { "user", "password", "host", "clientId", "topic","qos"}) public class EmqConnectConfiguration { }
 

4.使用的类中这样用

 

@SpringBootApplication public class DemoApplication { private static Userproperties user; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); System.out.println("toString:" + user.toString()); } public DemoApplication(Userproperties user) { this.user = user; } }
 

另一种:

把第二步中@Component放开,不需要第3步哪个配置文件,其他不变,照样用。