2021年8月4日 SpringBoot自定义配置获取
1、自定义了配置文件
praise.siteName = mahalalel
praise.siteUrl = http://127.0.0.1
2、配置文件配置
@ConfigurationProperties(prefix = "praise", value = "site.properties")
3、启动应用
报如下错误
In AnnotationAttributes for annotation [org.springframework.boot.context.properties.ConfigurationProperties] declared on class 'com.xxx.config.SiteConfig',
attribute 'prefix' and its alias 'value' are declared with values of [praise] and [site.properties],
but only one is permitted.
错误原因在于,注解ConfigurationProperties的属性prefix和value不能同时使用
4、修改并验证
@ConfigurationProperties(prefix = "praise")
public class SiteConfig {
private String siteName;
private String siteUrl;
// get/set方法省略
}
控制器内调用
@RestController
@RequestMapping("/task")
public class TaskController {
@Autowired
private SiteConfig siteConfig;
@GetMapping("/hello")
public String hello(){
String siteName = siteConfig.getSiteName();
return "Hello Task!!!!" + siteName;
}
}
访问地址:http://localhost:8081/task/hello
页面显示:
Hello Task!!!!mahalalel