文件配置
为了让 Spring Boot 更好的生成配置元数据文件,需要添加如下依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
application.yml
person:
address: 上海
name: Jack
Person:使用时注入属性即可
package com.smart.boot_mybatis.domain; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="person") public class Person { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", address='" + address + '\'' + '}'; } }
自定义配置文件
在Resources文件路径中,增加person.properties
person.address=china
person.name=Jim
package com.smart.boot_mybatis.domain; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @PropertySource("classpath:person.properties") @ConfigurationProperties(prefix="person") public class Person { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", address='" + address + '\'' + '}'; } }
springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件
–file:./config/
–file:./
–classpath:/config/
–classpath:/
优先级由高到底,高优先级的配置会覆盖低优先级的配置;可以通过spring.config.location来改变默认的配置文件位置
项目打包好以后,可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置;
java -jar boot-SNAPSHOT.jar --spring.config.location=D:/application.properties
立志如山 静心求实
浙公网安备 33010602011771号