书单推荐:成为Java顶级程序员架构师 ,这20来本(高薪)必看点击获取
把配置文件写到application.yml或application.properties中,有时我们不愿意把配置都写到application配置文件中,这时需要我们自定义配置文件,比如test.properties:
com.forezp.name=forezpcom.forezp.age=12
怎么将这个配置文件信息赋予给一个javabean呢?
@Configuration@PropertySource(value = "classpath:test.properties")@ConfigurationProperties(prefix = "com.forezp")public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
在最新版本的springboot,需要加这三个注解。@Configuration @PropertySource(value = “classpath:test.properties”) @ConfigurationProperties(prefix = “com.forezp”);在1.4版本需要 PropertySource加上location。
@RestController@EnableConfigurationProperties({ConfigBean.class,User.class})public class LucyController { @Autowired ConfigBean configBean; @RequestMapping(value = "/lucy") public String miya(){ return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax(); } @Autowired User user; @RequestMapping(value = "/user") public String user(){ return user.getName()+user.getAge(); }}
启动工程,打开localhost:8080/user;浏览器会显示:
forezp12