天天看点

Spring Boot 核心-外部配置

Spring Boot可以使用properties文件、yaml文件或者命令行参数作为外部配置。

1 命令行参数配置

Spring Boot可以基于jar包运行,打成jar包可以通过下面命令运行:

java -jar xxx.jar      

可以通过下面命令修改tomcate端口:

java -jar xx.jar --server.port=9090      

2 常规属性配置

常规Spring环境下,注入properties文件里的值的方式:

  1. 通过@PropertySource指明文件位置。
  2. 通过@Value注入值。

在Spring Boot环境下:

  1. 在application.properties中定义属性。
  2. 通过@Value注入值。

3 类型安全的配置(基于properties)

实战

  1. 新建Spring Boot项目
  2. 在pom中添加
<dependency>  
      <groupId>org.springframework.boot</groupId>  
      <artifactId>spring-boot-configuration-processor</artifactId>  
      <optional>true</optional>  
</dependency>      
  1. 在application.properties中添加配置
author.name=wyh
author.age=30      
  1. 类型安全的Bean
package com.chenfeng.xiaolyuh.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "author")// prefix指定properties的前缀,
public class AuthorSettings {
  private String name;
  
  private long age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public long getAge() {
    return age;
  }

  public void setAge(long age) {
    this.age = age;
  }
}      
  1. 校验代码
package com.chenfeng.xiaolyuh;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.chenfeng.xiaolyuh.properties.AuthorSettings;

@SpringBootApplication // 这个是Spring Boot项目的核心注解,主要是开启自动配置。
@RestController
public class SpringBootStudentApplication {

  @Autowired // 通过注解直接注入配置类
  private AuthorSettings authorSettings; 
  
  @RequestMapping("/")
  public String index() {
    return "Hello World!  " + authorSettings.getName() + "::" + authorSettings.getAge();
  }

  // 标准的JAVA应用main方法,主要作用作为项目启动的入口
  public static void main(String[] args) {
    SpringApplication.run(SpringBootStudentApplication.class, args);
  }

}      

继续阅读