SpringBoot(二):自定义配置

一、配置

  引入maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

  Spring Boot 默认 application.properties 文件,可以通过在文件中自定义属性,来替换默认属性

 

二、常见属性配置文件 application.properties

# 服务基础配置
server.port=8090 #服务启动的端口
spring.mvc.view.prefix=/WEB/INF/jsp #jsp文件默认前缀
spring.mvc.view.suffix=.jsp #响应默认后缀

#profile配置
spring.profiles.active #启用profile机制
spring.profiles.default #指定默认的profile,主要用于切换环境

#数据库配置
database.driverName=com.mysql.jdbc.Driver database.url=jdbc:mysql://localhost:3306/chapter3
database.username=root database.password=123456

 

三、引用配置文件

  1、@Value + ${}

@Component
public class DataBaseProperties {

     @Value("${database.driverName}")
     private String driverName = null;

     @Value("${database.url}")
     private String url = null;

   ...
}

  2、@ConfigurationProperties  自动组装properties文件中的key,规则:@ConfigurationProperties("key1") ,key1 + 属性名,例如database.url

@Component
@ConfigurationProperties("database")
public class DataBaseProperties {
    
     private String driverName = null;
     private String url = null;
     private String username = null;
     private String password = null;
     
 ...
}

 

四、自定义properties文件

@SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.chapter3"})
@PropertySource(value={"classpath:jdbc.properties"}, ignoreResourceNotFound=true)
public class Chapter3Application {
 public static void main(String[] args) {
     SpringApplication.run(Chapter3Application.class, args);
 }
}

 

五、profile使用

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>

posted @ 2018-10-07 22:44  刘广平  阅读(572)  评论(0)    收藏  举报