目录
Spring Boot的配置文件由两种形式:application.properties和application.yml两种配置方式。Spring Boot使用了一个全局的配置文件application.properties。Sping Boot的全局配置文件的作用是对一些默认配置的配置值进行修改。
一、配置文件基础
1.存放路径
application.properties和application.yml文件可以放在以下四个位置:
1).项目根目录下
2).项目根目录中config目录下
3).项目的resources目录下
4).项目resources目录中config目录下
2.读取顺序(优先级别)
如果在不同的目录中存在多个配置文件,它的读取顺序是:
1)、config/application.properties(项目根目录中config目录下)
2)、config/application.yml
3)、application.properties(项目根目录下)
4)、application.yml
5)、resources/config/application.properties(项目resources目录中config目录下)
6)、resources/config/application.yml
7)、resources/application.properties(项目的resources目录下)
8)、resources/application.yml
说明:
1)、如果同一个目录下,有application.yml也有application.properties,默认先读取application.properties。
2)、如果同一个配置属性,在多个配置文件都配置了,默认使用第1次读取到的,后面读取的不覆盖前面读取到的。
3)、创建SpringBoot项目时,一般的配置文件放置在“项目的resources目录下”
3.外部配置的加载顺序(较少用)

二、application.properties
1.自定义属性
application.properties支持自定义属性,我们可以将一些常量配置在这里。
1.1简单属性
##-------简单值配置-----------------
com.bj.name="zhangsan"
com.bj.sex="男"
直接在要使用的地方通过注解@Value(value=”${config.name}”)就可以绑定到想要的属性上面.
@RestController
public class HelloConller{
@Value("${com.bj.name}")
private String name;
@Value("${com.bj.sex}")
private String sex;
@RequestMapping("/info")
public String info(){
return name+","+sex;
}
}
此时,启动项目,并访问http://localhost:8080/,则可以在页面中看到
1.2实体属性
有时候属性太多了,一个个绑定到属性字段上比较麻烦,官方提倡绑定一个对象的bean(实体)上,建一个User.java类,并在类上添加注解@ConfigurationProperties(prefix = “com.bj”)来指明使用哪个属性集。
注意:在配置文件中可以配置多个前缀不同但最后的字符串相同的信息,同时使用该信息时,也需要指明到具体的属性前缀。eg:
com.bj.name="张三"
com.name="hatao"
name="lisi"
代表三个不同的配置信息。
@ConfigurationProperties(prefix = "com.bj")
@Validated //数据校验
public class User{
private String name;
private String sex;
//ConfigurationProperties下,支持JSR303数据校验,校验是邮箱格式
@email
private String email;
// 省略getter和setter
}
还需要配置@EnableConfigurationProperties并指明要加载哪个bean。其配置方式为:
a).在入口类SpringBoot01Application中,添加该注解并指定需要加载的bean
@SpringBootApplication
@EnableConfigurationProperties({User.class})
public class Springboot01Application {
public static void main(String[] args) {
SpringApplication.run(Springboot01Application.class, args);
}
}
@EnableConfigurationProperties注解。该注解是用来开启对@ConfigurationProperties注解配置Bean的支持。也就是@EnableConfigurationProperties注解告诉Spring Boot 能支持@ConfigurationProperties。如果不指定会看到异常。
然后在Controller中引用该User即可以。
@RestController
public class UserController {
@Autowired
private User user;
@RequestMapping(value = "/userinfo")
public String userInfo(){
return "实体对象信息:"+user.getName()+","+user.getSex();
}
}

参考:https://www.cnblogs.com/duanxz/p/4520571.html
1.3参数间引用
在该配置文件中各个参数之间可以直接引用来使用。
com.bj.name="zhangsan"
com.bj.sex="男"
#-------------------
com.bj.info=姓名${com.bj.name},性别${com.bj.sex}
@RestController
public class UserController {
@Value("${com.bj.info}")
private String info;
@RequestMapping(value = "/userinfo2")
public String userInfo2(){
return "参数引用信息:"+info;
}
}

1.4随机值配置
配置文件中${random} 可以用来生成各种不同类型的随机值,从而简化了代码生成的麻烦,例如 生成 int 值、long 值或者 string 字符串。
##-------随机值配置-----------------
com.bj.secret=${random.value}
com.bj.number=${random.int}
com.bj.bignumber=${random.long}
com.bj.uuid=${random.uuid}
com.bj.number.less.than.ten=${random.int(10)}
com.bj.number.in.range=${random.int[1024,65536]}
com.bj.random=${com.bj.secret},${com.bj.number},${com.bj.bignumber},${com.bj.uuid},${com.bj.number.less.than.ten},${com.bj.number.in.range}
@RestController
public class RandomController {
@Value("${com.bj.random}")
private String random;
@RequestMapping(value = "/random")
public String random(){
return "随机值信息:"+random;
}
}

1.5自定义配置文件
有时候不希望把所有配置都放在application.properties里面,这时候可以另外定义一个,取名为test.properties(此处取名随意),路径也放在src/main/resources下面。
此时需要新建一个类,添加注解@Configuration,使其成为一个配置类,并通过注解使其和自定义的配置文件关联。
@Configuration
@ConfigurationProperties(prefix = "com.bj.test")
@PropertySource("classpath:test.properties")
public class ConfigTest {
private String name;
private String sex;
// 省略getter和setter
}
其中@Configuration表明当前类为配置文件;@PropertySource指明所要加载的文件;@ConfigurationProperties标注对应的属性集。
2.常用属性
2.1多环境配置profile
当应用程序需要部署到不同运行环境时,一些配置细节通常会有所不同,最简单的比如日志,生产日志会将日志级别设置为WARN或更高级别,并将日志写入日志文件,而开发的时候需要日志级别为DEBUG,日志输出到控制台即可。
如果按照以前的做法,就是每次发布的时候替换掉配置文件,这样太麻烦了,Spring Boot的Profile就给我们提供了解决方案。1)profile配置文件
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识。
比如:现有三个文件application-dev.properties为开发环境,application-prod.properties为生产环境,application-test.properties为测试环境
想要使用其中对应的环境,只需在application.properties文件中设置属性spring.profiles.active,其值为上面提到的{profile},如dev、prod、test。
spring.profiles.active=dev
若设置如上,则springboot 会加载使用 application.properties 和 application-dev.properties 配置文件的信息。
2).yml配置文件文档块的方式:
具体文档块参考下面application.xml的介绍。
server:
port: 8080
spring:
profiles:
active: dev
---
spring:
profiles: dev
server:
port: 8081
---
spring:
profiles: prod
server:
port: 8082
3)@Profile注解(了解)
除了可以用profile的配置文件来分区配置我们的环境变量,在代码里,我们还可以直接用@Profile注解来进行配置,例如数据库配置。
定义一个接口,并分别定义两个实现类
public interface DBConnector { public void configure(); }
/*** 测试数据库 */
@Component
@Profile("testdb")
public class TestDBConnector implements DBConnector {
@Override
public void configure() {
System.out.println("testdb");
}
}
/*** 生产数据库 */
@Component
@Profile("devdb")
public class DevDBConnector implements DBConnector {
@Override
public void configure() {
System.out.println("devdb");
}
}
通过在配置文件激活具体使用哪个实现类
spring.profiles.active=testdb
然后就可以在控制器中使用
@RestController
@RequestMapping("/task")
public class TaskController {
@Autowired
DBConnector connector ;
@RequestMapping(value = {"/",""})
public String hellTask(){
connector.configure(); //最终打印testdb
return "hello task !! myage is " + myage;
}
}
4)叠加profile
spring.profiles.include 的作用是可以叠加激活新的profile,即可能存在多个配置文件需要切换激活
spring.profiles.include=dev,DevFTP,devDB,devRedis
5).命令行方式
将项目打包,通过命令行传参数的方式
或调试方式


6).虚拟机参数的方式

三、application.yml
1.yaml语法
- 使用缩进表示层级关系
- 缩进不适用Tab,使用空格
- 大小写敏感
2.格式
key:(空格)value:表示一个键值对,空格必须
3.支持的值
普通自变量:
a: "123"
数组(List、Set)
a: [a,b,c]
或
a:
- a
- b
- c
对象(Map)
friends: {firstname: zhang,lastname: san}
或者
friends:
fristname: zhang
lastname: san
4.其他
文档快:在yml配置文件中输入---,则可切换文档块
四、其他
1.添加组件:添加组件的方式有两种
1).传统方式:
- 新建一个传统的spring配置文件,如bean.xml,其内部采用<bean></bean>的方式添加组件;
- 在启动类上通过注解@ImportResource(locations={"classpath:bean.xml"})的方式注入
2).springboot推荐方式:全注解
- 新建一个类,加注解@Configuration,使其成为一个配置类(等价于传统方式的bean.xml),其内部采用@Bean的方式添加;
- 在类上新建一个方法并添加注解@Bean,其作用就是将方法的返回值添加到容器中,其默认 id为方法名
@Configuration
public class myConfig {
@Bean
public HelloService helloService() {
return new HelloServiceImpl();
}
}
五、常用应用程序属性
参考http://tengj.top/2017/02/28/springbootconfig/
# ===================================================================
# COMMON SPRING BOOT PROPERTIES
#
# This sample file is provided as a guideline. Do NOT copy it in its
# entirety to your own application. ^^^
# ===================================================================
# ----------------------------------------
# CORE PROPERTIES
# ----------------------------------------
# BANNER
banner.charset=UTF-8 # Banner file encoding.
banner.location=classpath:banner.txt # Banner file location.
banner.image.location=classpath:banner.gif # Banner image file location (jpg/png can also be used).
banner.image.width= # Width of the banner image in chars (default 76)
banner.image.height= # Height of the banner image in chars (default based on image height)
banner.image.margin= # Left hand image margin in chars (default 2)
banner.image.invert= # If images should be inverted for dark terminal themes (default false)
# LOGGING
logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name. For instance `myapp.log`
logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
logging.path= # Location of the log file. For instance `/var/log`
logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.
# AOP
spring.aop.auto=true # Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class=false # Whether subclass-based (CGLIB) proxies are to be created (true) as opposed to standard Java interface-based proxies (false).
# IDENTITY (ContextIdApplicationContextInitializer)
spring.application.index= # Application index.
spring.application.name= # Application name.
# ADMIN (SpringApplicationAdminJmxAutoConfiguration)
spring.application.admin.enabled=false # Enable admin features for the application.
spring.application.admin.jmx-name=org.springframework.boot:type=Admin,name=SpringApplication # JMX name of the application admin MBean.
# AUTO-CONFIGURATION
spring.autoconfigure.exclude= # Auto-configuration classes to exclude.
# SPRING CORE
spring.beaninfo.ignore=true # Skip search of BeanInfo classes.
# SPRING CACHE (CacheProperties)
spring.cache.cache-names= # Comma-separated list of cache names to create if supported by the underlying cache manager.
spring.cache.caffeine.spec= # The spec to use to create caches. Check CaffeineSpec for more details on the spec format.
spring.cache.couchbase.expiration=0 # Entry expiration in milliseconds. By default the entries never expire.
spring.cache.ehcache.config= # The location of the configuration file to use to initialize EhCache.
spring.cache.guava.spec= # The spec to use to create caches. Check CacheBuilderSpec for more details on the spec format.
spring.cache.hazelcast.config= # The location of the configuration file to use to initialize Hazelcast.
spring.cache.infinispan.config= # The location of the configuration file to use to initialize Infinispan.
spring.cache.jcache.config= # The location of the configuration file to use to initialize the cache manager.
spring.cache.jcache.provider= # Fully qualified name of the CachingProvider implementation to use to retrieve the JSR-107 compliant cache manager. Only needed if more than one JSR-107 implementation is available on the classpath.
spring.cache.type= # Cache type, auto-detected according to the environment by default.
# SPRING CONFIG - using environment property only (ConfigFileApplicationListener)
spring.config.location= # Config file locations.
spring.config.name=application # Config file name.
# HAZELCAST (HazelcastProperties)
spring.hazelcast.config= # The location of the configuration file to use to initialize Hazelcast.
# PROJECT INFORMATION (ProjectInfoProperties)
spring.info.build.location=classpath:META-INF/build-info.properties # Location of the generated build-info.properties file.
spring.info.git.location=classpath:git.properties # Location of the generated git.properties file.
# JMX
spring.jmx.default-domain= # JMX domain name.
spring.jmx.enabled=true # Expose management beans to the JMX domain.
spring.jmx.server=mbeanServer # MBeanServer bean name.
# Email (MailProperties)
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
spring.mail.host= # SMTP server host. For instance `smtp.example.com`
spring.mail.jndi-name= # Session JNDI name. When set, takes precedence to others mail settings.
spring.mail.password= # Login password of the SMTP server.
spring.mail.port= # SMTP server port.
spring.mail.properties.*= # Additional JavaMail session properties.
spring.mail.protocol=smtp # Protocol used by the SMTP server.
spring.mail.test-connection=false # Test that the mail server is available on startup.
spring.mail.username= # Login user of the SMTP server.
# APPLICATION SETTINGS (SpringApplication)
spring.main.banner-mode=console # Mode used to display the banner when the application runs.
spring.main.sources= # Sources (class name, package name or XML resource location) to include in the ApplicationContext.
spring.main.web-environment= # Run the application in a web environment (auto-detected by default).
# FILE ENCODING (FileEncodingApplicationListener)
spring.mandatory-file-encoding= # Expected character encoding the application must use.
# INTERNATIONALIZATION (MessageSourceAutoConfiguration)
spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding=UTF-8 # Message bundles encoding.
spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found.
# OUTPUT
spring.output.ansi.enabled=detect # Configure the ANSI output.
# PID FILE (ApplicationPidFileWriter)
spring.pid.fail-on-write-error= # Fail if ApplicationPidFileWriter is used but it cannot write the PID file.
spring.pid.file= # Location of the PID file to write (if ApplicationPidFileWriter is used).
# PROFILES
spring.profiles.active= # Comma-separated list (or list if using YAML) of active profiles.
spring.profiles.include= # Unconditionally activate the specified comma separated profiles (or list of profiles if using YAML).
# SENDGRID (SendGridAutoConfiguration)
spring.sendgrid.api-key= # SendGrid api key (alternative to username/password)
spring.sendgrid.username= # SendGrid account username
spring.sendgrid.password= # SendGrid account password
spring.sendgrid.proxy.host= # SendGrid proxy host
spring.sendgrid.proxy.port= # SendGrid proxy port
# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------
# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.address= # Network address to which the server should bind to.
server.compression.enabled=false # If response compression is enabled.
server.compression.excluded-user-agents= # List of user-agents to exclude from compression.
server.compression.mime-types= # Comma-separated list of MIME types that should be compressed. For instance `text/html,text/css,application/json`
server.compression.min-response-size= # Minimum response size that is required for compression to be performed. For instance 2048
server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout.
server.context-parameters.*= # Servlet context init parameters. For instance `server.context-parameters.a=alpha`
server.context-path= # Context path of the application.
server.display-name=application # Display name of the application.
server.max-http-header-size=0 # Maximum size in bytes of the HTTP message header.
server.error.include-stacktrace=never # When to include a "stacktrace" attribute.
server.error.path=/error # Path of the error controller.
server.error.whitelabel.enabled=true # Enable the default error page displayed in browsers in case of a server error.
server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content

最低0.47元/天 解锁文章
10万+

被折叠的 条评论
为什么被折叠?



