1 问题描述
从之前@Value的使用,可以知道@Value可以灵活的把配置文件中的键值对的值注入到Bean中供我们使用,已经很灵活了,但这还不够,比如下述的application.properties
tomcat.ip=192.168.1.110
tomcat.port=8787
tomcat.projectName=screenshot
tomcat.userName=admin
tomcat.password=admin
如果也要按照之前的描述,使用@value就要填写5次,这显然令人惆怅,在程序员的世界里,所有重复性的工作都应该被取代,因此Spring Boot为我们提供了@ConfigurationProperties注解。
2 实践
2.1 application.properties
tomcat.ip=192.168.1.110
tomcat.port=8787
tomcat.projectName=screenshot
从上述的配置项中,可以看到明显的相似性,即这一簇配置均以tomcat开始,类似String类中的startWith函数。
2.1 核心代码
package com.wisely.ch6_2_3.config;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "tomcat") //1
@Log4j
public class TomcatSetting {
@Getter
@Setter
private String ip;
@Getter
@Setter
private int port;
@Getter
@Setter
private String projectName;
public String getUrl() {
return "http://"+getIp()+"/"+getPort()+"/"+getProjectName();
}
}
通过这种方法,即可实现一次性注入相似的配置,非常方便。
减少了重复性工作,即提高优雅度,也能减少错误,很酷。
3参考
Spring使用@Value和@PropertySource注入外部资源
SpringBoot中实用@Value注入配置文件中的配置