1. 程式人生 > >Spring Boot屬性配置

Spring Boot屬性配置

resource req http mar ref 還需 gpo .config 應用程序

1. Spring Boot的默認配置文件application.properties或者appliaction.yml

2. 自定義屬性有多種方法:

2.1對於引用少數幾個屬性值,可以直接使用@Value註解直接引用自定義屬性值,不需要@Configuration等註解配合.

application.properties提供自定義屬性的支持,這樣我們就可以把一些常量配置在這裏:

com.windy.name="windy"
com.windy.want="祝大家新年好"

然後直接在要使用的地方通過註解@Value(value=”${config.name}”)就可以綁定到你想要的屬性上面

@RestController
public class UserController {

    @Value("${com.windy.name}")
    private  String name;
    @Value("${com.windy.want}")
    private  String want;

    @RequestMapping("/")
    public String hexo(){
        return name+","+want;
    }
}

2.2 有時候屬性太多,一個個綁定太累,官方提倡綁定一個對象的Bean.

實現這種方式需要3個步驟:

這裏我們新建一個Java類ConfigBean,並在這個類上加上註解@Configuration(下圖少了這個註解)

@Configuration
@ConfigurationProperties(prefix = "com.windy")
//@PropertySource(classpath:application.properties)
public class ConfigBean {
    private String name;
    private String want;
 
    // 省略getter和setter
}

  

還需要在spring Boot入口類加上@EnableConfigurationProperties

@SpringBootApplication
@EnableConfigurationProperties()
public class Chapter2Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter2Application.class, args);
    }
}

最後在Controller中引入ConfigBean使用即可

@RestController
public class UserController {
    @Autowired
    ConfigBean configBean;

    @RequestMapping("/")
    public String hexo(){
        return configBean.getName()+configBean.getWant();
    }
}

  

3. 配置文件的優先級

application.properties和application.yml文件可以放在以下四個位置:

  • 外置,在相對於應用程序運行目錄的/congfig子目錄裏。
  • 外置,在應用程序運行的目錄裏
  • 內置,在config包內
  • 內置,在Classpath根目錄

同樣,這個列表按照優先級排序,也就是說,src/main/resources/config下application.properties覆蓋src/main/resources下application.properties中相同的屬性,如圖:

技術分享圖片

此外,如果你在相同優先級位置同時有application.properties和application.yml,那麽application.properties裏的屬性裏面的屬性就會覆蓋application.yml。

4. 使用@Profile註解進行配置

首先定義一個DBConnect的接口

@Component
public interface DBConnector {

	public void configure();
	
}

然後分別定義Mysql和Oracle的實現類

@Component
@Profile("Mysql")
public class MysqlConnector implements DBConnector {

	@Override
	public void configure() {
		System.out.println("This is Mysql!");
	}

}

@Component
@Profile("Oracle")
public class OracleConnector implements DBConnector {

	@Override
	public void configure() {
		System.out.println("This is Oracle!");
	}

}

在配置文件application.properties中指定使用哪個實現類

spring.profiles.active=Oracle

然後就可以這麽用了

@RestController
public class DBContorller {
	
	@Autowired
	DBConnector dbConnector;
	
	@RequestMapping("/db")
	public void dbConnector(){
		
		dbConnector.configure(); //最終打印"This is Oracle!"
		
	}
	
}

  

除了spring.profiles.active來激活一個或者多個profile之外,還可以用spring.profiles.include來疊加profile

spring.profiles.active: Oracle  
spring.profiles.include: proddb,prodmq

  

Spring Boot屬性配置