11月17, 2018

Spring Boot(五) 自定义配置

#SpringBoot 自定义配置 这里要说的自定义配置主要是两类:一类是关于Spring MVC的扩展配置,一类是Spring Boot自身通过配置文件的自定义配置 首先,我们来看一下SpringBoot中关于Spring MVC的相关配置

Spring MVC配置

SpringBoot中肯定以及帮我们配置好了相关的Spring MVC内容,我们在SpringBoot官方文档中可以看到相关介绍

  • Inclusion of ContentNegotiatingViewResolver andBeanNameViewResolverbeans.
  • Support for serving static resources, including support for WebJars (see below).
  • Automatic registration of Converter, GenericConverter, Formatter beans.
  • Support for HttpMessageConverters (see below).
  • Automatic registration of MessageCodesResolver (see below).
  • Static index.html support.
  • Custom Favicon support (see below).
  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

上面这段是官方文档的原话,简单来说,就是SpringBoot已经帮我们配置了欢迎首页,静态资源,Favicon,视图解析器,转换器,格式化转换,转换Http请求和响应等等.只要你用过Spring MVC,一些基本的配置就不需要你再配置了,按照SpringBoot的默认配置约定,就能够直接上手使用

WebMvcConfigurerAdapter与@Configuration

当然,基本配置肯定不够我们使用的,那如果我们要自定义一下Spring MVC的配置该怎么办,其实关键就在这句话:

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

这段话已经解释的很清楚了,如果我们需要自己配置内容,比如拦截器,格式化器,以及视图解析器等等,仅仅需要自己写一个类,继承WebMvcConfigurerAdapter,并且加上@Configuration注解就可以了,不过注意不要加上@EnableWebMvc这个注解.

打开WebMvcConfigurerAdapter的源代码,你可以看到这个类是一个抽象类,实现了WebMvcConfigurer接口中的所有方法,其实就是一个中介类。在WebMvcConfigurerAdapter类中,下面的这些方法都是我们常用的:

/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;
/** 添加拦截器 **/
void addInterceptors(InterceptorRegistry registry);
/** 这里配置视图解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);
/** 配置内容裁决的一些选项 **/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/** 视图跳转控制器 **/
void addViewControllers(ViewControllerRegistry registry);
/** 静态资源处理 **/
void addResourceHandlers(ResourceHandlerRegistry registry);
/** 默认静态资源处理器 **/
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);

这个自定义配置有什么意义?举一个简单例子,比如现在我们需要从后台跳转到视图success.html,那么至少需要在Controller中定义一个空的方法,这个方法就是定义,你在浏览器上输入什么值,然后跳转到什么页面,比如下面的这个样子:

@Controller
public class HelloController {
    @RequestMapping(value="/v")
    public String success() {
        return "success";
    }
}

这样子的跳转,其实我们也完全可以在配置中完成,不需要再到Controller中为了一个简单跳转,就创建一个空的方法. 简单来说,其实Spring Boot就是可以写代码添加配置类的方式,来完成以前需要在XML中配置的事情 现在我们就自己写一个配置类,来完成视图的跳转 -w996

WebMvcConfig.java

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //浏览器发送 /v 请求来到视图 success 页面
        registry.addViewController("/v").setViewName("success");
    }

}

现在没有Controller中的方法,在浏览器中输入127.0.0.1:8080/v也能跳转到success视图页面

@EnableWebMvc

注意在官方文档中还有这么一句话:

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

意思是如果想全面接管Spring MVC,不需要Spring Boot的自定义控制,那么只需要再加上 @EnableWebMvc这么一个注解就行了,这么做的话相当于所有的Spring MVC的相关配置都需要自己手动再写一次,这个就看个人的需求了

如果你想更深入的理解,可以看一下源代码,其实是在EnableWebMvc接口中导入了DelegatingWebMvcConfiguration类,而这个类又是WebMvcConfigurationSupport的子类,所以,归根结底一句话:如果Spring Boot发现在容器中有WebMvcConfigurationSupport的子类,那么就会忽略所有的自定义配置,你就要在这个子类中配置好Spring MVC所有的相关配置

当然,上面所说的并不是太重要,你只是方便大家自行去研究,重要在下面的这一点

Spring Boot2.0

Spring Boot2.0中,WebMvcConfigurerAdapter已经是属于一个被废弃的方法,所以,要实现自动以WebMvc的配置类,只能是下面的两种方式:

1.实现WebMvcConfigurer接口:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  //省略
}

2.继承WebMvcConfigurationSupport类:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
  //省略
}

我们上面才刚刚解释了如果在Spring Boot容器中发现了WebMvcConfigurationSupport的子类,等于说全部的自定义配置就失效了,所以,第二种方式并不太推荐

其实不用纠结,之所以Spring Boot2.0直接废弃了WebMvcConfigurerAdapter类,是由于Spring Boot2.0之后只支持JDK1.8以上版本了,在JDK1.8之前,使用一个抽象类作为接口的中间类,完全是为了让我们自己的实现类不至于去实现一个接口中所有的方法,简化操作我们实现类的代码而已.JDK1.8之后,接口有了新的扩展,在接口中还可以定义staticdefault方法,static定义的方法,可以通过接口名直接调用,和一般的静态方法一样,default定义的方法,可以直接有实现

所以,在Spring Boot2.0之后,我们就可以直接去实现WebMvcConfigurer接口就可以了

自定义配置类的内容主要是SpringMVC的一些相关配置,如果我们要定义整个工程相关的一些自定义配置,就需要使用配置文件进行配置

Spring Boot配置文件

Spring Boot提供了properties和yml两种配置文件的方式

properties文件

创建好项目之后,能看到Spring Boot默认会在src/main/resources下帮你创建一个application.properties文件 -w238 默认是一个空文件,不过Spring Boot已经帮你默认配置好了很多项,如果你需要指定的你的项目的启动端口,和上下文根路径,可以在配置文件中写入下面的配置:

server.port=8888
server.context-path=/yingside

也就是说现在我们浏览器访问程序的端口就是8888,而且也必须加上/yingside项目路径 -w769

YAML文件

YAML,全称Yet Another Markup Language,是“另一种标记语言”的外语缩写. 这里就不再对YAML语法做过多了解释了,简单来说,其实YAML文件就是在使用时,比properties文件多了一些格式上的要求,而且使用的 key: value的格式.最重要的格式注意项就是:后面,value值前面要有空格,不然就是错误的 大致格式如下:

key: 
 key1: value1
 key2: value2

因此,上面的properties文件,如果用yaml文件(文件后缀可以是.yaml或者.yml)表示,就是下面这个样子:

server:
  port: 8888
  context-path: /yingside

当然yaml语法还有很多细节,不过这些并不是学习的重点,有需要的时候再去查阅就行了

注意:默认eclispe没有对yaml文件的支持,所以在yml书写时并不是太方便,你可以下载插件在线更新 Help --> Install New Software --> 添加新的插件,地址: http://dadacoalition.org/yedit

两种配置文件的基本格式就是这个样子,至于配置文件中可以配置的内容,那就多了去了,下面是官方文档中给出的所有在配置文件中可以配置的内容,给大家列举了出来,需要的时候可以进行查阅

application.properties

# ----------------------------------------
# CORE PROPERTIES
# ----------------------------------------

# SPRING 相关配置 (ConfigFileApplicationListener)
spring.config.name= # config file name (default to 'application')
spring.config.location= # location of config file

# profile相关配置
spring.profiles= # comma list of active profiles

# 系统配置相关参数 (SpringApplication)
spring.main.sources=
spring.main.web-environment= # detect by default
spring.main.show-banner=true
spring.main....= # see class for all properties

# 日志配置相关参数
logging.path=/var/logs
logging.file=myapp.log
logging.config=

# IDENTITY (ContextIdApplicationContextInitializer)
spring.application.name=
spring.application.index=

# tomcat相关配置参数 (ServerProperties)
server.port=8080
server.address= # bind to a specific NIC
server.session-timeout= # session timeout in seconds
server.context-path= # the context path, defaults to '/'
server.servlet-path= # the servlet path, defaults to '/'
server.tomcat.access-log-pattern= # log pattern of the access log
server.tomcat.access-log-enabled=false # is access logging enabled
server.tomcat.protocol-header=x-forwarded-proto # ssl forward headers
server.tomcat.remote-ip-header=x-forwarded-for
server.tomcat.basedir=/tmp # base dir (usually not needed, defaults to tmp)
server.tomcat.background-processor-delay=30; # in seconds
server.tomcat.max-threads = 0 # number of threads in protocol handler
server.tomcat.uri-encoding = UTF-8 # character encoding to use for URL decoding

# springmvc相关配置参数 (HttpMapperProperties)
http.mappers.json-pretty-print=false # pretty print JSON
http.mappers.json-sort-keys=false # sort keys
spring.mvc.locale= # set fixed locale, e.g. en_UK
spring.mvc.date-format= # set fixed date format, e.g. dd/MM/yyyy
spring.mvc.message-codes-resolver-format= # PREFIX_ERROR_CODE / POSTFIX_ERROR_CODE
spring.view.prefix= # MVC view prefix
spring.view.suffix= # ... and suffix
spring.resources.cache-period= # cache timeouts in headers sent to browser
spring.resources.add-mappings=true # if default mappings should be added

# thymeleaf相关配置参数 (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=true # set to false for hot refresh

# freemark相关配置参数 (FreeMarkerAutoConfiguration)
spring.freemarker.allowRequestOverride=false
spring.freemarker.allowSessionOverride=false
spring.freemarker.cache=true
spring.freemarker.checkTemplateLocation=true
spring.freemarker.contentType=text/html
spring.freemarker.exposeRequestAttributes=false
spring.freemarker.exposeSessionAttributes=false
spring.freemarker.exposeSpringMacroHelpers=false
spring.freemarker.prefix=
spring.freemarker.requestContextAttribute=
spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.viewNames= # whitelist of view names that can be resolved

# groovy模板相关配置参数 (GroovyTemplateAutoConfiguration)
spring.groovy.template.allowRequestOverride=false
spring.groovy.template.allowSessionOverride=false
spring.groovy.template.cache=true
spring.groovy.template.configuration.*= # See Groovy's TemplateConfiguration
spring.groovy.template.contentType=text/html
spring.groovy.template.prefix=classpath:/templates/
spring.groovy.template.suffix=.tpl
spring.groovy.template.templateEncoding=UTF-8
spring.groovy.template.viewNames= # whitelist of view names that can be resolved

# velocity模板相关配置参数 (VelocityAutoConfiguration)
spring.velocity.allowRequestOverride=false
spring.velocity.allowSessionOverride=false
spring.velocity.cache=true
spring.velocity.checkTemplateLocation=true
spring.velocity.contentType=text/html
spring.velocity.dateToolAttribute=
spring.velocity.exposeRequestAttributes=false
spring.velocity.exposeSessionAttributes=false
spring.velocity.exposeSpringMacroHelpers=false
spring.velocity.numberToolAttribute=
spring.velocity.prefix=
spring.velocity.properties.*=
spring.velocity.requestContextAttribute=
spring.velocity.resourceLoaderPath=classpath:/templates/
spring.velocity.suffix=.vm
spring.velocity.templateEncoding=UTF-8
spring.velocity.viewNames= # whitelist of view names that can be resolved

# INTERNATIONALIZATION (MessageSourceAutoConfiguration)
spring.messages.basename=messages
spring.messages.cacheSeconds=-1
spring.messages.encoding=UTF-8


# 安全相关配置参数 (SecurityProperties)
security.user.name=user # login username
security.user.password= # login password
security.user.role=USER # role assigned to the user
security.require-ssl=false # advanced settings ...
security.enable-csrf=false
security.basic.enabled=true
security.basic.realm=Spring
security.basic.path= # /**
security.headers.xss=false
security.headers.cache=false
security.headers.frame=false
security.headers.contentType=false
security.headers.hsts=all # none / domain / all
security.sessions=stateless # always / never / if_required / stateless
security.ignored=false

# 数据源相关配置参数(DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.name= # name of the data source
spring.datasource.initialize=true # populate using data.sql
spring.datasource.schema= # a schema (DDL) script resource reference
spring.datasource.data= # a data (DML) script resource reference
spring.datasource.platform= # the platform to use in the schema resource (schema-${platform}.sql)
spring.datasource.continueOnError=false # continue even if can't be initialized
spring.datasource.separator=; # statement separator in SQL initialization scripts
spring.datasource.driverClassName= # JDBC Settings...
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.max-active=100 # Advanced configuration...
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
spring.datasource.validation-query=
spring.datasource.test-on-borrow=false
spring.datasource.test-on-return=false
spring.datasource.test-while-idle=
spring.datasource.time-between-eviction-runs-millis=
spring.datasource.min-evictable-idle-time-millis=
spring.datasource.max-wait-millis=

# mongdb相关配置参数 (MongoProperties)
spring.data.mongodb.host= # the db host
spring.data.mongodb.port=27017 # the connection port (defaults to 27107)
spring.data.mongodb.uri=mongodb://localhost/test # connection URL
spring.data.mongo.repositories.enabled=true # if spring data repository support is enabled

# springDataJPA相关配置参数(JpaBaseConfiguration, HibernateJpaAutoConfiguration)
spring.jpa.properties.*= # properties to set on the JPA connection
spring.jpa.openInView=true
spring.jpa.show-sql=true
spring.jpa.database-platform=
spring.jpa.database=
spring.jpa.generate-ddl=false # ignored by Hibernate, might be useful for other vendors
spring.jpa.hibernate.naming-strategy= # naming classname
spring.jpa.hibernate.ddl-auto= # defaults to create-drop for embedded dbs
spring.data.jpa.repositories.enabled=true # if spring data repository support is enabled

# solr相关配置参数(SolrProperties})
spring.data.solr.host=http://127.0.0.1:8983/solr
spring.data.solr.zkHost=
spring.data.solr.repositories.enabled=true # if spring data repository support is enabled

# elasticsearch相关配置参数(ElasticsearchProperties})
spring.data.elasticsearch.cluster-name= # The cluster name (defaults to elasticsearch)
spring.data.elasticsearch.cluster-nodes= # The address(es) of the server node (comma-separated; if not specified starts a client node)
spring.data.elasticsearch.local=true # if local mode should be used with client nodes
spring.data.elasticsearch.repositories.enabled=true # if spring data repository support is enabled



# flyway相关配置参数(FlywayProperties)
flyway.locations=classpath:db/migrations # locations of migrations scripts
flyway.schemas= # schemas to update
flyway.initVersion= 1 # version to start migration
flyway.prefix=V
flyway.suffix=.sql
flyway.enabled=true
flyway.url= # JDBC url if you want Flyway to create its own DataSource
flyway.user= # JDBC username if you want Flyway to create its own DataSource
flyway.password= # JDBC password if you want Flyway to create its own DataSource

# liquibase相关配置参数(LiquibaseProperties)
liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml
liquibase.contexts= # runtime contexts to use
liquibase.default-schema= # default database schema to use
liquibase.drop-first=false
liquibase.enabled=true

# JMX
spring.jmx.enabled=true # Expose MBeans from Spring

# rabbitmq相关配置参数(RabbitProperties)
spring.rabbitmq.host= # connection host
spring.rabbitmq.port= # connection port
spring.rabbitmq.addresses= # connection addresses (e.g. myhost:9999,otherhost:1111)
spring.rabbitmq.username= # login user
spring.rabbitmq.password= # login password
spring.rabbitmq.virtualhost=
spring.rabbitmq.dynamic=

# redis相关配置参数(RedisProperties)
spring.redis.host=localhost # server host
spring.redis.password= # server password
spring.redis.port=6379 # connection port
spring.redis.pool.max-idle=8 # pool settings ...
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

# activemq相关配置参数(ActiveMQProperties)
spring.activemq.broker-url=tcp://localhost:61616 # connection URL
spring.activemq.user=
spring.activemq.password=
spring.activemq.in-memory=true # broker kind to create if no broker-url is specified
spring.activemq.pooled=false

# hornetq相关配置参数(HornetQProperties)
spring.hornetq.mode= # connection mode (native, embedded)
spring.hornetq.host=localhost # hornetQ host (native mode)
spring.hornetq.port=5445 # hornetQ port (native mode)
spring.hornetq.embedded.enabled=true # if the embedded server is enabled (needs hornetq-jms-server.jar)
spring.hornetq.embedded.serverId= # auto-generated id of the embedded server (integer)
spring.hornetq.embedded.persistent=false # message persistence
spring.hornetq.embedded.data-directory= # location of data content (when persistence is enabled)
spring.hornetq.embedded.queues= # comma separate queues to create on startup
spring.hornetq.embedded.topics= # comma separate topics to create on startup
spring.hornetq.embedded.cluster-password= # customer password (randomly generated by default)

# JMS (JmsProperties)
spring.jms.pub-sub-domain= # false for queue (default), true for topic

# springbatch相关配置参数(BatchDatabaseInitializer)
spring.batch.job.names=job1,job2
spring.batch.job.enabled=true
spring.batch.initializer.enabled=true
spring.batch.schema= # batch schema to load

# aop相关配置参数
spring.aop.auto=
spring.aop.proxy-target-class=

# FILE ENCODING (FileEncodingApplicationListener)
spring.mandatory-file-encoding=false

# SPRING SOCIAL (SocialWebAutoConfiguration)
spring.social.auto-connection-views=true # Set to true for default connection views or false if you provide your own

# SPRING SOCIAL FACEBOOK (FacebookAutoConfiguration)
spring.social.facebook.app-id= # your application's Facebook App ID
spring.social.facebook.app-secret= # your application's Facebook App Secret

# SPRING SOCIAL LINKEDIN (LinkedInAutoConfiguration)
spring.social.linkedin.app-id= # your application's LinkedIn App ID
spring.social.linkedin.app-secret= # your application's LinkedIn App Secret

# SPRING SOCIAL TWITTER (TwitterAutoConfiguration)
spring.social.twitter.app-id= # your application's Twitter App ID
spring.social.twitter.app-secret= # your application's Twitter App Secret

# SPRING MOBILE SITE PREFERENCE (SitePreferenceAutoConfiguration)
spring.mobile.sitepreference.enabled=true # enabled by default

# SPRING MOBILE DEVICE VIEWS (DeviceDelegatingViewResolverAutoConfiguration)
spring.mobile.devicedelegatingviewresolver.enabled=true # disabled by default
spring.mobile.devicedelegatingviewresolver.normalPrefix=
spring.mobile.devicedelegatingviewresolver.normalSuffix=
spring.mobile.devicedelegatingviewresolver.mobilePrefix=mobile/
spring.mobile.devicedelegatingviewresolver.mobileSuffix=
spring.mobile.devicedelegatingviewresolver.tabletPrefix=tablet/
spring.mobile.devicedelegatingviewresolver.tabletSuffix=

# ----------------------------------------
# ACTUATOR PROPERTIES
# ----------------------------------------

# MANAGEMENT HTTP SERVER (ManagementServerProperties)
management.port= # defaults to 'server.port'
management.address= # bind to a specific NIC
management.contextPath= # default to '/'

# ENDPOINTS (AbstractEndpoint subclasses)
endpoints.autoconfig.id=autoconfig
endpoints.autoconfig.sensitive=true
endpoints.autoconfig.enabled=true
endpoints.beans.id=beans
endpoints.beans.sensitive=true
endpoints.beans.enabled=true
endpoints.configprops.id=configprops
endpoints.configprops.sensitive=true
endpoints.configprops.enabled=true
endpoints.configprops.keys-to-sanitize=password,secret
endpoints.dump.id=dump
endpoints.dump.sensitive=true
endpoints.dump.enabled=true
endpoints.env.id=env
endpoints.env.sensitive=true
endpoints.env.enabled=true
endpoints.health.id=health
endpoints.health.sensitive=false
endpoints.health.enabled=true
endpoints.info.id=info
endpoints.info.sensitive=false
endpoints.info.enabled=true
endpoints.metrics.id=metrics
endpoints.metrics.sensitive=true
endpoints.metrics.enabled=true
endpoints.shutdown.id=shutdown
endpoints.shutdown.sensitive=true
endpoints.shutdown.enabled=false
endpoints.trace.id=trace
endpoints.trace.sensitive=true
endpoints.trace.enabled=true

# MVC ONLY ENDPOINTS
endpoints.jolokia.path=jolokia
endpoints.jolokia.sensitive=true
endpoints.jolokia.enabled=true # when using Jolokia
endpoints.error.path=/error

# JMX ENDPOINT (EndpointMBeanExportProperties)
endpoints.jmx.enabled=true
endpoints.jmx.domain= # the JMX domain, defaults to 'org.springboot'
endpoints.jmx.unique-names=false
endpoints.jmx.enabled=true
endpoints.jmx.staticNames=

# JOLOKIA (JolokiaProperties)
jolokia.config.*= # See Jolokia manual

# REMOTE SHELL
shell.auth=simple # jaas, key, simple, spring
shell.command-refresh-interval=-1
shell.command-path-pattern= # classpath*:/commands/**, classpath*:/crash/commands/**
shell.config-path-patterns= # classpath*:/crash/*
shell.disabled-plugins=false # don't expose plugins
shell.ssh.enabled= # ssh settings ...
shell.ssh.keyPath=
shell.ssh.port=
shell.telnet.enabled= # telnet settings ...
shell.telnet.port=
shell.auth.jaas.domain= # authentication settings ...
shell.auth.key.path=
shell.auth.simple.user.name=
shell.auth.simple.user.password=
shell.auth.spring.roles=

# GIT INFO
spring.git.properties= # resource ref to generated git info properties file

本文链接:http://www.yanhongzhi.com/post/springboot-config.html

-- EOF --

Comments