SpringBoot资料整理(7)

Spring Boot 属性配置和使用

spring Boot 允许通过外部配置让你在不同的环境使用同一应用程序的代码,简单说就是可以通过配置文件来注入属性或者修改默认的配置。

Spring Boot 支持多种外部配置方式

这些方式优先级如下:

  1. 命令行参数
  2. 来自java:comp/env的JNDI属性
  3. Java系统属性(System.getProperties()
  4. 操作系统环境变量
  5. RandomValuePropertySource配置的random.*属性值
  6. jar包外部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  7. jar包内部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  8. jar包外部的application.propertiesapplication.yml(不带spring.profile)配置文件
  9. jar包内部的application.propertiesapplication.yml(不带spring.profile)配置文件
  10. @Configuration注解类上的@PropertySource
  11. 通过SpringApplication.setDefaultProperties指定的默认属性

命令行参数

通过Java -jar app.jar --name="Spring" --server.port=9090方式来传递参数。

参数用--xxx=xxx的形式传递。

可以使用的参数可以是我们自己定义的,也可以是Spring Boot中默认的参数。

很多人可能会关心如web端口如何配置这样的问题,这些都是Spring Boot中提供的参数,部分可用参数如下:

# LOGGING
logging.path=/var/logs
logging.file=myapp.log
logging.config= # location of config file (default classpath:logback.xml for logback)
logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'

更多常见的应用属性请浏览这里

注意:命令行参数在app.jar的后面!

可以通过SpringApplication.setAddCommandLineProperties(false)禁用命令行配置。

Java系统属性

注意Java系统属性位置java -Dname="isea533" -jar app.jar,可以配置的属性都是一样的,优先级不同。

例如java -Dname="isea533" -jar app.jar --name="Spring!"name值为Spring!

操作系统环境变量

配置过JAVA_HOME的应该都了解这一个。

这里需要注意的地方,有些OS可以不支持使用.这种名字,如server.port,这种情况可以使用SERVER_PORT来配置。

具体名字如何匹配,看本文后面。

RandomValuePropertySource

系统中用到随机数的地方,例如:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

random.int*支持value参数和,max参数,当提供max参数的时候,value就是最小值。

应用配置文件(.properties或.yml)

在配置文件中直接写:

name=Isea533
server.port=8080

.yml格式的配置文件如:

name: Isea533
server:
    port: 8080

当有前缀的情况下,使用.yml格式的配置文件更简单。关于.yml配置文件用法请看这里

注意:使用.yml时,属性名的值和冒号中间必须有空格,如name: Isea533正确,name:Isea533就是错的。

属性配置文件的位置

spring会从classpath下的/config目录或者classpath的根目录查找application.propertiesapplication.yml

/config优先于classpath根目录

@PropertySource

这个注解可以指定具体的属性配置文件,优先级比较低。

SpringApplication.setDefaultProperties

例如:

SpringApplication application = new SpringApplication(Application.class);
Map<String, Object> defaultMap = new HashMap<String, Object>();
defaultMap.put("name", "Isea-Blog");
//还可以是Properties对象
application.setDefaultProperties(defaultMap);
application.run(args);

应用(使用)属性

@Value(“${xxx}”)

这种方式是最简单的,通过@Value注解可以将属性值注入进来。

@ConfigurationProperties

Spring Boot 可以方便的将属性注入到一个配置对象中。例如:

my.name=Isea533
my.port=8080
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

对应对象:

@ConfigurationProperties(prefix="my")
public class Config {
    private String name;
    private Integer port;
    private List<String> servers = new ArrayList<String>();

    public String geName(){
        return this.name;
    }

    public Integer gePort(){
        return this.port;
    }
    public List<String> getServers() {
        return this.servers;
    }
}

Spring Boot 会自动将prefix="my"前缀为my的属性注入进来。

Spring Boot 会自动转换类型,当使用List的时候需要注意在配置中对List进行初始化!

Spring Boot 还支持嵌套属性注入,例如:

name=isea533
jdbc.username=root
jdbc.password=root
...

对应的配置类:

@ConfigurationProperties
public class Config {
    private String name;
    private Jdbc jdbc;
    class Jdbc {
        private String username;
        private String password;
        //getter...
    }

    public Integer gePort(){
        return this.port;
    }
    public Jdbc getJdbc() {
        return this.jdbc;
    }
}

jdbc开头的属性都会注入到Jdbc对象中。

在@Bean方法上使用@ConfigurationProperties

例如:

@ConfigurationProperties(prefix = "foo")
@Bean
public FooComponent fooComponent() {
    ...
}
  •  

Spring Boot 会将foo开头的属性按照名字匹配注入到FooComponent对象中。

属性占位符

例如:

app.name=MyApp
app.description=${app.name} is a Spring Boot application

可以在配置文件中引用前面配置过的属性(优先级前面配置过的这里都能用)。

通过如${app.name:默认名称}方法还可以设置默认值,当找不到引用的属性时,会使用默认的属性。

由于${}方式会被Maven处理。如果你pom继承的spring-boot-starter-parent,Spring Boot 已经将maven-resources-plugins默认的${}方式改为了@ @方式,例如@name@

如果你是引入的Spring Boot,你可以修改使用其他的分隔符

通过属性占位符还能缩短命令参数

例如修改web默认端口需要使用--server.port=9090方式,如果在配置中写上:

server.port=${port:8080}

那么就可以使用更短的--port=9090,当不提供该参数的时候使用默认值8080

属性名匹配规则

例如有如下配置对象:

@Component
@ConfigurationProperties(prefix="person")
public class ConnectionSettings {

    private String firstName;

}

firstName可以使用的属性名如下:

  1. person.firstName,标准的驼峰式命名
  2. person.first-name,虚线(-)分割方式,推荐在.properties.yml配置文件中使用
  3. PERSON_FIRST_NAME,大写下划线形式,建议在系统环境变量中使用

属性验证

可以使用JSR-303注解进行验证,例如:

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

最后

以上是Spring Boot 属性配置和使用的内容,有些不全面的地方或者读者有更多疑问,可以查看Spring Boot完整文档 或 Externalized Configuration

关于Spring Boot更多的内容可以继续关注本博客。

下面补充一部分常用配置:

mvc

  • spring.mvc.async.request-timeout
    设定async请求的超时时间,以毫秒为单位,如果没有设置的话,以具体实现的超时时间为准,比如tomcat的servlet3的话是10秒.

  • spring.mvc.date-format
    设定日期的格式,比如dd/MM/yyyy.

  • spring.mvc.favicon.enabled
    是否支持favicon.ico,默认为: true

  • spring.mvc.ignore-default-model-on-redirect
    在重定向时是否忽略默认model的内容,默认为true

  • spring.mvc.locale
    指定使用的Locale.

  • spring.mvc.message-codes-resolver-format
    指定message codes的格式化策略(PREFIX_ERROR_CODE,POSTFIX_ERROR_CODE).

  • spring.mvc.view.prefix
    指定mvc视图的前缀.

  • spring.mvc.view.suffix
    指定mvc视图的后缀.

messages

  • spring.messages.basename
    指定message的basename,多个以逗号分隔,如果不加包名的话,默认从classpath路径开始,默认: messages

  • spring.messages.cache-seconds
    设定加载的资源文件缓存失效时间,-1的话为永不过期,默认为-1

  • spring.messages.encoding
    设定Message bundles的编码,默认: UTF-8

mobile

  • spring.mobile.devicedelegatingviewresolver.enable-fallback
    是否支持fallback的解决方案,默认false

  • spring.mobile.devicedelegatingviewresolver.enabled
    是否开始device view resolver,默认为: false

  • spring.mobile.devicedelegatingviewresolver.mobile-prefix
    设定mobile端视图的前缀,默认为:mobile/

  • spring.mobile.devicedelegatingviewresolver.mobile-suffix
    设定mobile视图的后缀

  • spring.mobile.devicedelegatingviewresolver.normal-prefix
    设定普通设备的视图前缀

  • spring.mobile.devicedelegatingviewresolver.normal-suffix
    设定普通设备视图的后缀

  • spring.mobile.devicedelegatingviewresolver.tablet-prefix
    设定平板设备视图前缀,默认:tablet/

  • spring.mobile.devicedelegatingviewresolver.tablet-suffix
    设定平板设备视图后缀.

  • spring.mobile.sitepreference.enabled
    是否启用SitePreferenceHandler,默认为: true

view

  • spring.view.prefix
    设定mvc视图的前缀.

  • spring.view.suffix
    设定mvc视图的后缀.

resource

  • spring.resources.add-mappings
    是否开启默认的资源处理,默认为true

  • spring.resources.cache-period
    设定资源的缓存时效,以秒为单位.

  • spring.resources.chain.cache
    是否开启缓存,默认为: true

  • spring.resources.chain.enabled
    是否开启资源 handling chain,默认为false

  • spring.resources.chain.html-application-cache
    是否开启h5应用的cache manifest重写,默认为: false

  • spring.resources.chain.strategy.content.enabled
    是否开启内容版本策略,默认为false

  • spring.resources.chain.strategy.content.paths
    指定要应用的版本的路径,多个以逗号分隔,默认为:[/**]

  • spring.resources.chain.strategy.fixed.enabled
    是否开启固定的版本策略,默认为false

  • spring.resources.chain.strategy.fixed.paths
    指定要应用版本策略的路径,多个以逗号分隔

  • spring.resources.chain.strategy.fixed.version
    指定版本策略使用的版本号

  • spring.resources.static-locations
    指定静态资源路径,默认为classpath:[/META-INF/resources/,/resources/, /static/, /public/]以及context:/

multipart

  • multipart.enabled
    是否开启文件上传支持,默认为true

  • multipart.file-size-threshold
    设定文件写入磁盘的阈值,单位为MB或KB,默认为0

  • multipart.location
    指定文件上传路径.

  • multipart.max-file-size
    指定文件大小最大值,默认1MB

  • multipart.max-request-size
    指定每次请求的最大值,默认为10MB

freemarker

  • spring.freemarker.allow-request-override
    指定HttpServletRequest的属性是否可以覆盖controller的model的同名项

  • spring.freemarker.allow-session-override
    指定HttpSession的属性是否可以覆盖controller的model的同名项

  • spring.freemarker.cache
    是否开启template caching.

  • spring.freemarker.charset
    设定Template的编码.

  • spring.freemarker.check-template-location
    是否检查templates路径是否存在.

  • spring.freemarker.content-type
    设定Content-Type.

  • spring.freemarker.enabled
    是否允许mvc使用freemarker.

  • spring.freemarker.expose-request-attributes
    设定所有request的属性在merge到模板的时候,是否要都添加到model中.

  • spring.freemarker.expose-session-attributes
    设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中.

  • spring.freemarker.expose-spring-macro-helpers
    设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用

  • spring.freemarker.prefer-file-system-access
    是否优先从文件系统加载template,以支持热加载,默认为true

  • spring.freemarker.prefix
    设定freemarker模板的前缀.

  • spring.freemarker.request-context-attribute
    指定RequestContext属性的名.

  • spring.freemarker.settings
    设定FreeMarker keys.

  • spring.freemarker.suffix
    设定模板的后缀.

  • spring.freemarker.template-loader-path
    设定模板的加载路径,多个以逗号分隔,默认: ["classpath:/templates/"]

  • spring.freemarker.view-names
    指定使用模板的视图列表.

velocity

  • spring.velocity.allow-request-override
    指定HttpServletRequest的属性是否可以覆盖controller的model的同名项

  • spring.velocity.allow-session-override
    指定HttpSession的属性是否可以覆盖controller的model的同名项

  • spring.velocity.cache
    是否开启模板缓存

  • spring.velocity.charset
    设定模板编码

  • spring.velocity.check-template-location
    是否检查模板路径是否存在.

  • spring.velocity.content-type
    设定ContentType的值

  • spring.velocity.date-tool-attribute
    设定暴露给velocity上下文使用的DateTool的名

  • spring.velocity.enabled
    设定是否允许mvc使用velocity

  • spring.velocity.expose-request-attributes
    是否在merge模板的时候,将request属性都添加到model中

  • spring.velocity.expose-session-attributes
    是否在merge模板的时候,将HttpSession属性都添加到model中

  • spring.velocity.expose-spring-macro-helpers
    设定是否以springMacroRequestContext的名来暴露RequestContext给Spring’s macro类库使用

  • spring.velocity.number-tool-attribute
    设定暴露给velocity上下文的NumberTool的名

  • spring.velocity.prefer-file-system-access
    是否优先从文件系统加载模板以支持热加载,默认为true

  • spring.velocity.prefix
    设定velocity模板的前缀.

  • spring.velocity.properties
    设置velocity的额外属性.

  • spring.velocity.request-context-attribute
    设定RequestContext attribute的名.

  • spring.velocity.resource-loader-path
    设定模板路径,默认为: classpath:/templates/

  • spring.velocity.suffix
    设定velocity模板的后缀.

  • spring.velocity.toolbox-config-location
    设定Velocity Toolbox配置文件的路径,比如 /WEB-INF/toolbox.xml.

  • spring.velocity.view-names
    设定需要解析的视图名称.

thymeleaf

  • spring.thymeleaf.cache
    是否开启模板缓存,默认true

  • spring.thymeleaf.check-template-location
    是否检查模板路径是否存在,默认true

  • spring.thymeleaf.content-type
    指定Content-Type,默认为: text/html

  • spring.thymeleaf.enabled
    是否允许MVC使用Thymeleaf,默认为: true

  • spring.thymeleaf.encoding
    指定模板的编码,默认为: UTF-8

  • spring.thymeleaf.excluded-view-names
    指定不使用模板的视图名称,多个以逗号分隔.

  • spring.thymeleaf.mode
    指定模板的模式,具体查看StandardTemplateModeHandlers,默认为: HTML5

  • spring.thymeleaf.prefix
    指定模板的前缀,默认为:classpath:/templates/

  • spring.thymeleaf.suffix
    指定模板的后缀,默认为:.html

  • spring.thymeleaf.template-resolver-order
    指定模板的解析顺序,默认为第一个.

  • spring.thymeleaf.view-names
    指定使用模板的视图名,多个以逗号分隔.

mustcache

  • spring.mustache.cache
    是否Enable template caching.

  • spring.mustache.charset
    指定Template的编码.

  • spring.mustache.check-template-location
    是否检查默认的路径是否存在.

  • spring.mustache.content-type
    指定Content-Type.

  • spring.mustache.enabled
    是否开启mustcache的模板支持.

  • spring.mustache.prefix
    指定模板的前缀,默认: classpath:/templates/

  • spring.mustache.suffix
    指定模板的后缀,默认: .html

  • spring.mustache.view-names
    指定要使用模板的视图名.

groovy模板

  • spring.groovy.template.allow-request-override
    指定HttpServletRequest的属性是否可以覆盖controller的model的同名项

  • spring.groovy.template.allow-session-override
    指定HttpSession的属性是否可以覆盖controller的model的同名项

  • spring.groovy.template.cache
    是否开启模板缓存.

  • spring.groovy.template.charset
    指定Template编码.

  • spring.groovy.template.check-template-location
    是否检查模板的路径是否存在.

  • spring.groovy.template.configuration.auto-escape
    是否在渲染模板时自动排查model的变量,默认为: false

  • spring.groovy.template.configuration.auto-indent
    是否在渲染模板时自动缩进,默认为false

  • spring.groovy.template.configuration.auto-indent-string
    如果自动缩进启用的话,是使用SPACES还是TAB,默认为: SPACES

  • spring.groovy.template.configuration.auto-new-line
    渲染模板时是否要输出换行,默认为false

  • spring.groovy.template.configuration.base-template-class
    指定template base class.

  • spring.groovy.template.configuration.cache-templates
    是否要缓存模板,默认为true

  • spring.groovy.template.configuration.declaration-encoding
    在写入declaration header时使用的编码

  • spring.groovy.template.configuration.expand-empty-elements
    是使用<br/>这种形式,还是<br></br>这种展开模式,默认为: false)

  • spring.groovy.template.configuration.locale
    指定template locale.

  • spring.groovy.template.configuration.new-line-string
    当启用自动换行时,换行的输出,默认为系统的line.separator属性的值

  • spring.groovy.template.configuration.resource-loader-path
    指定groovy的模板路径,默认为classpath:/templates/

  • spring.groovy.template.configuration.use-double-quotes
    指定属性要使用双引号还是单引号,默认为false

  • spring.groovy.template.content-type
    指定Content-Type.

  • spring.groovy.template.enabled
    是否开启groovy模板的支持.

  • spring.groovy.template.expose-request-attributes
    设定所有request的属性在merge到模板的时候,是否要都添加到model中.

  • spring.groovy.template.expose-session-attributes
    设定所有request的属性在merge到模板的时候,是否要都添加到model中.

  • spring.groovy.template.expose-spring-macro-helpers
    设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用

  • spring.groovy.template.prefix
    指定模板的前缀.

  • spring.groovy.template.request-context-attribute
    指定RequestContext属性的名.

  • spring.groovy.template.resource-loader-path
    指定模板的路径,默认为: classpath:/templates/

  • spring.groovy.template.suffix
    指定模板的后缀

  • spring.groovy.template.view-names
    指定要使用模板的视图名称.

http

  • spring.hateoas.apply-to-primary-object-mapper
    设定是否对object mapper也支持HATEOAS,默认为: true

  • spring.http.converters.preferred-json-mapper
    是否优先使用JSON mapper来转换.

  • spring.http.encoding.charset
    指定http请求和相应的Charset,默认: UTF-8

  • spring.http.encoding.enabled
    是否开启http的编码支持,默认为true

  • spring.http.encoding.force
    是否强制对http请求和响应进行编码,默认为true

json

  • spring.jackson.date-format
    指定日期格式,比如yyyy-MM-dd HH:mm:ss,或者具体的格式化类的全限定名

  • spring.jackson.deserialization
    是否开启Jackson的反序列化

  • spring.jackson.generator
    是否开启json的generators.

  • spring.jackson.joda-date-time-format
    指定Joda date/time的格式,比如yyyy-MM-dd HH:mm:ss). 如果没有配置的话,dateformat会作为backup

  • spring.jackson.locale
    指定json使用的Locale.

  • spring.jackson.mapper
    是否开启Jackson通用的特性.

  • spring.jackson.parser
    是否开启jackson的parser特性.

  • spring.jackson.property-naming-strategy
    指定PropertyNamingStrategy (CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)或者指定PropertyNamingStrategy子类的全限定类名.

  • spring.jackson.serialization
    是否开启jackson的序列化.

  • spring.jackson.serialization-inclusion
    指定序列化时属性的inclusion方式,具体查看JsonInclude.Include枚举.

  • spring.jackson.time-zone
    指定日期格式化时区,比如America/Los_Angeles或者GMT+10.

jersey

  • spring.jersey.filter.order
    指定Jersey filter的order,默认为: 0

  • spring.jersey.init
    指定传递给Jersey的初始化参数.

  • spring.jersey.type
    指定Jersey的集成类型,可以是servlet或者filter.

转载于:https://my.oschina.net/undefine/blog/849484

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值