主配置文件使用
Spring Boot的主配置文件默认为application.properties,必须放在源代码文件夹根目录下,一般放在src/main/resources下
application.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
server.port=9080
使用主配置文件中的配置项的两种方式
@Value
完整的注解路径名为org.springframework.beans.factory.annotation.Value;
Environment
完整类路径org.springframework.core.env.Environment;
使用Demo
package driver.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@Data
public class ConfigHelper {
/**
* 第一种读取核心配置文件application.properties
*/
@Autowired
private Environment env;
@Value("${server.port}")
private String property;
}
自定义配置文件使用
比如在src/main/resources目录下有一个customed-config文件夹,保存自定义配置文件
myconfig.properties
test.custom.property=Hello~~
使用自定义配置文件的方式
package driver.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="test.custom")
@PropertySource("classpath:/customed-configs/myconfig.properties")
@Data
/**
* 读取自定义配置文件
* @author wuhui.wwh
*/
public class MyConfig {
private String property;
}