springboot读取配置方法:
一、简单引用
1、在app.properties文件中编写内容,
com.redxun.name = 测试
com.redxun.want = spring boot
com.redxun.sum = ${com.redxun.name} +${com.redxun.want}
2、在controller中使用:
@RestController
@EnableConfigurationProperties({ConfigBean.class})
public class UserController {
@Autowired
ConfigBean configBean;
@RequestMapping("/")
public String index(){
return "Hello spring boot!" + configBean.getSum();
}
}
3、配置文件实体类:
@Component
@ConfigurationProperties(prefix = "com.redxun")
public class ConfigBean {
private String name;
private String want;
private String sum;
/*
get/set
*/
}
4、app.properties内容在页面显示乱码问题:
如图,勾上Transparent native-to-ascii conversion即可。
5、最终效果:
二、扩展引用:
1、引用自定义的properties文件:
新建一个test.properties文件,引入方式跟缺省配置文件几乎一样,区别在于在此需要制定引用路径:
@Configuration
@ConfigurationProperties(prefix = "com.md")
@PropertySource("classpath:test.properties") // 指定引用路径
参考资料:springboot干货