玩转Spring Boot 自定义配置、导入XML配置与外部化配置

摘要:
玩SpringBoot自定义配置,导入XML配置和外部配置。这里我将全面介绍如何在SpringBoot中定制配置,更改SpringBoot的默认配置,并介绍每个配置的优先级顺序。此外,Spring Boot支持多种配置名称的方式,例如server.ssl。密钥存储,可以写成server.ssl.keyStore。
玩转Spring Boot 自定义配置、导入XML配置与外部化配置

      在这里我会全面介绍在Spring Boot里面如何自定义配置,更改Spring Boot默认的配置,以及介绍各配置的优先级顺序。Spring Boot使用一个全局的配置文件application.properties,Spring Boot 支持使用YAML语言的配置文件,YAML是以数据位中心的语言,所以使用application.yml作为全局配置也是同样的效果,如果使用YAML替代properties注意写法,冒号后面要加个空格,否则会解析不出来。而且在Spring Boot里面配置名称支持多种方式,例如:server.ssl.key-store,可以写成:server.ssl.keyStore都是可以的。下面具体详细介绍。

1.引用XML文件配置

      在实际项目中有的情况需要使用到XML配置文件,或者是你还不习惯用Java 配置的方式,那么你可以通过在入口启动类上加上@ImportResource(value = { "路径" })或者使用@ImportResource(locations= { "路径" }),一样的效果,多个XML文件的话你可以用逗号“,”分隔,就这样轻而易举的引用XML配置。

2.引入多个@Configuration 配置类

      在实际项目中可能不会把所有的配置都放在一个配置类(用@Configuration注解的类)中,可能会分开配置。这时可以用@Import注解引用。

3.引用自定义properties

      Spring Boot使用全局配置(application.properties)提供了很多的默认的配置属性。在开发的时候,大多数会用到自定义的一些配置属性,例如:指定上传文件保存的路径,定义:file.upload.stor-path=E:/test/,Spring Boot 提供了@Value注解获取properties中的属性,还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性注入到一个Bean中,在1.4以上版本官方不建议使用@ConfigurationProperties来指定properties文件位置。接下来请看实例:
      在pom.xml中加入以下依赖:
  1. <dependency>    
  2.           <groupId>org.springframework.boot</groupId>    
  3.           <artifactId>spring-boot-configuration-processor</artifactId>    
  4.           <optional>true</optional>    
  5. </dependency>   
<dependency>  
          <groupId>org.springframework.boot</groupId>  
          <artifactId>spring-boot-configuration-processor</artifactId>  
          <optional>true</optional>  
</dependency> 

第一种:
     (1) 在src/main/resources下新建application.properties文件并加入以下代码:
  1. file.upload.stor-path=E:/test/  
file.upload.stor-path=E:/test/
      (2)直接使用@Value注解方式,具体代码如下:
  1. package com.chengli.springboot.helloworld;  
  2.   
  3. import org.springframework.beans.factory.annotation.Value;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. @RestController  
  10. @SpringBootApplication  
  11. public class SampleController {  
  12.     @Value(value = "${file.upload.stor-path}")  
  13.     private String storPath;  
  14.   
  15.     @RequestMapping("/")  
  16.     String home() {  
  17.         return "Hello World! file.upload.stor-path为:" + storPath;  
  18.     }  
  19.   
  20.     public static void main(String[] args) throws Exception {  
  21.         SpringApplication springApplication = new SpringApplication(SampleController.class);  
  22.         springApplication.run(args);  
  23.     }  
  24. }  
package com.chengli.springboot.helloworld;

import org.springframework.beans.factory.annotation.Value;
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;

@RestController
@SpringBootApplication
public class SampleController {
@Value(value = "${file.upload.stor-path}")
private String storPath;

@RequestMapping("/")
String home() {
	return "Hello World! file.upload.stor-path为:" + storPath;
}

public static void main(String[] args) throws Exception {
	SpringApplication springApplication = new SpringApplication(SampleController.class);
	springApplication.run(args);
}

}

第二种:
      属性配置放在application.properties文件中,使用@ConfigurationProperties将配置属性注入到Bean中,代码如下:
      (1)定义FileUploadProperties类
  1. package com.chengli.springboot.helloworld;  
  2.   
  3. import org.springframework.boot.context.properties.ConfigurationProperties;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. @Component  
  7. @ConfigurationProperties(prefix = "file.upload")  
  8. public class FileUploadProperties {  
  9.     private String storPath;  
  10.   
  11.     public String getStorPath() {  
  12.         return storPath;  
  13.     }  
  14.   
  15.     public void setStorPath(String storPath) {  
  16.         this.storPath = storPath;  
  17.     }  
  18. }  
package com.chengli.springboot.helloworld;

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

@Component
@ConfigurationProperties(prefix = "file.upload")
public class FileUploadProperties {
private String storPath;

public String getStorPath() {
	return storPath;
}

public void setStorPath(String storPath) {
	this.storPath = storPath;
}

}

      (2)入口启动类代码如下:
  1. package com.chengli.springboot.helloworld;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. @RestController  
  10. @SpringBootApplication  
  11. public class SampleController {  
  12.     @Autowired  
  13.     private FileUploadProperties fileUploadProperties;  
  14.   
  15.     @RequestMapping("/")  
  16.     String home() {  
  17.         return "Hello World! file.upload.stor-path为:" + fileUploadProperties.getStorPath();  
  18.     }  
  19.   
  20.     public static void main(String[] args) throws Exception {  
  21.         SpringApplication springApplication = new SpringApplication(SampleController.class);  
  22.         springApplication.run(args);  
  23.     }  
  24. }  
package com.chengli.springboot.helloworld;

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;

@RestController
@SpringBootApplication
public class SampleController {
@Autowired
private FileUploadProperties fileUploadProperties;

@RequestMapping("/")
String home() {
	return "Hello World! file.upload.stor-path为:" + fileUploadProperties.getStorPath();
}

public static void main(String[] args) throws Exception {
	SpringApplication springApplication = new SpringApplication(SampleController.class);
	springApplication.run(args);
}

}

      注意:这里我对FileUploadProperties使用了@Component注解,如果没有使用@Component注解,则需要在入口启动类上加上@EnableConfigurationProperties注解。Spring Boot 在properties文件中支持使用SpEL表达式,可以进行校验(校验注解使用的是javax.validation)等操作。
例如以下:
(1)随机数:
          test.int.random=${random.int}
(2)数组注入
          test.int.random[0]=${random.int}
          test.int.random[1]=${random.int}
(3)校验
         @NotNull
         private String storPath;

4.外部化配置(配置方式与优先级)

      Spring Boot 允许外化配置,Spring Boot使用了一个特别的PropertySource次序来允许对值进行覆盖,覆盖的优先级顺序如下:
  (1)Devtools全局设置主目录(~ /.spring-boot-devtools.properties 为活跃的)。
  (2)@TestPropertySource注解在Test。
  (3)@SpringBootTest#properties 注解在Test。
  (4)命令行参数。
  (5)从SPRING_APPLICATION_JSON属性(内联JSON嵌入在一个环境变量或系统属性)。
  (6)ServletConfig init参数。
  (7)ServletContext init参数。
  (8)JNDI属性java:comp/env。
  (9)Java系统属性(System.getProperties())。
  (10)操作系统环境变量。
  (11)RandomValuePropertySource配置的random.*属性值
  (12)打包在jar以外的application-{profile}.properties或application.yml配置文件
  (13)打包在jar以内的application-{profile}.properties或application.yml配置文件
  (14)打包在jar以外的application.properties或application.yml配置文件
  (15)打包在jar以内的application.properties或application.yml配置文件
  (16)@configuration注解类上的@PropertySource。
  (17)默认的属性(使用SpringApplication.setDefaultProperties指定)。

a) 通过命令行来修改默认参数,例如:
     启动命令:java -jar *.jar --name="chengli"
     以上的意思是,将name值修改为:chengli
b) 通过命令行来设置加载properties 例如:
     java -jar *.jar --spring.profiles.active=dev
     这里如果不了解profile的话,后面的文章中会介绍到。


5.application.properties文件按优先级,优先级高的会覆盖优先级低的

   优先级顺序如下:
  (1)当前目录下的一个/config子目录
  (2)当前目录
  (3)一个classpath下的/config包
  (4)classpath根目录


有兴趣的朋友可以加群探讨相互学习:

Spring Boot QQ交流群:599546061

免责声明:文章转载自《玩转Spring Boot 自定义配置、导入XML配置与外部化配置》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Oracle RAC 全局等待事件 gc current block busy 和 gc cr multi block request 说明--转载(http://blog.csdn.net/tianlesoftware/article/details/7777511)Pandas之Series+DataFrame下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

使用 Fresco加载图片

概念: ImagePipeline ——负责从网络、本地图片、Content Provider(内容提供者)或者本地资源那里获取图片,压缩保存在本地存储中和在内存中保存为压缩的图片 Drawee——处理图片的渲染,由3部分组成: (1)DraweeView——显示图片的View,继承ImageView;大部分时间将使用SimpleDraweeView (2...

Android检测版本更新

一、准备       1.检测当前版本的信息AndroidManifest.xml-->manifest-->android:versionName。       2.从服务器获取版本号(版本号存在于xml文件中)并与当前检测到的版本进行匹配,如果不匹配,提示用户进行升级,如果匹配则进入程序主界面。       3.当提示用户进行版本升级时,如...

SpringBoot1.x升级SpringBoot2.x踩坑之文件上传大小限制

SpringBoot1.x升级SpringBoot2.x踩坑之文件上传大小限制 前言 LZ最近升级SpringBoo框架到2.1.6,踩了一些坑,这里介绍的是文件上传大小限制。 升级前 #文件上传配置 1.5.9 spring: http: multipart: enabled: tr...

jquery中ajax的dataType属性包括哪几项

参考ajax api文档:http://www.w3school.com.cn/jquery/ajax_ajax.aspdataType类型:String预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML。在 1.4 中,JSON 就会生成一个 JavaSc...

marshaller unmarshaller解析xml和读取xml

JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到XML实例文档。从另一方面来讲,JAXB提供了快速而简便的方法将XML模式绑定到Java表示,从而...

Druid连接池的简单使用

感谢原文作者:chenhongyong原文链接:https://www.cnblogs.com/chy18883701161/p/12594889.html更多请查阅阿里官方API文档:https://github.com/alibaba/druid/wiki 目录 Druid简介 druid的优点 Druid的使用 方式一:纯代码方式 方式二:配置...