spring-boot(0) application.properties配置文件和自定义配置文件

一,要修改启动的端口

只需要创建application.properties文件然后 加上一行

server.port=8083

既可


二,配置自定义常量

比如application.properties有 port=8081 

@Value("${port:8082}")
private String port;

即可获取8081这个值


三,单独的java对象映射

application.properties有如下配置:

connection.url=localhst
connection.username=gao
connection.remoteAddress=127.0.0.1
connection.password=123
对应的java文件:

@Component
@ConfigurationProperties(prefix = "connection")
public class AppConfig {
	private String url;
	private String username;
	private String remoteAddress;
	private String password;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getRemoteAddress() {
		return remoteAddress;
	}

	public void setRemoteAddress(String remoteAddress) {
		this.remoteAddress = remoteAddress;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String toString() {
		return "[url=" + url + ", username=" + username + ", remoteAddress=" + remoteAddress + ", password=" + password
				+ "]";
	}

}

使用的时候,

@Autowired
AppConfig appcf;
即可



四,单独的配置文件,比如db.properties

db1.host=localhost
db1.port=80
db1.name=root
db1.psw=123


需要建立一个java类

@Component
@ConfigurationProperties(prefix="db1",locations="classpath:db.properties")
public class DBConfig {
	private String name;
	private String psw;
	private String host;
	private String port;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPsw() {
		return psw;
	}
	public void setPsw(String psw) {
		this.psw = psw;
	}
	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	@Override
	public String toString() {
		return "DBConfig [name=" + name + ", psw=" + psw + ", host=" + host + ", port=" + port + "]";
	}
	
}

然后用的时候

	@Autowired
	DBConfig dbf;

即可

在工程的配置文件不是非常复杂的情况下,推荐使用第三种方法

你可能感兴趣的:(spring-boot)