美文网首页我爱编程
springboot 06 ‘How-to’ guides

springboot 06 ‘How-to’ guides

作者: Herman7z | 来源:发表于2018-03-22 14:41 被阅读0次

    1. Customize the Environment or ApplicationContext before it starts

    A SpringApplication has ApplicationListeners and ApplicationContextInitializers that are used to apply customizations to the context or environment. Spring Boot loads a number of such customizations for use internally from META-INF/spring.factories. There is more than one way to register additional ones:
    Programmatically per application by calling the addListeners and addInitializers methods onSpringApplication before you run it.
    Declaratively per application by setting context.initializer.classes orcontext.listener.classes.
    Declaratively for all applications by adding a META-INF/spring.factories and packaging a jar file that the applications all use as a library.
    The SpringApplication sends some special ApplicationEvents to the listeners (even some before the context is created), and then registers the listeners for events published by the ApplicationContext as well. See Section 23.5, “Application events and listeners” in the ‘Spring Boot features’ section for a complete list.
    It is also possible to customize the Environment before the application context is refreshed usingEnvironmentPostProcessor. Each implementation should be registered in META-INF/spring.factories:
    org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor

    2. Automatic property expansion using Maven (使用Maven扩展配置)

    2.1 如果你使用的 spring-boot-starter-parent ,那么你可以直接使用@..@

    <profiles>
        <profile>
            <id>development</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <server.port>8000</server.port>
            </properties>
        </profile>
    </profiles>
    

    在application.properties文件中配置
    server.port=@server.port@

    2.2 如果你不是使用的 spring-boot-starter-parent ,那么在pom.xml内插入以下代码:

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    

    接着添加插件:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.7</version>
        <configuration>
            <delimiters>
                <delimiter>@</delimiter>
            </delimiters>
            <useDefaultDelimiters>false</useDefaultDelimiters>
        </configuration>
    </plugin>
    

    这个插件默认的方式是${...},为了避免和Spring的方式冲突,这里禁用了默认的方式,使用@...@

    3. Externalize the configuration of SpringApplication

    SpringApplication可以通过编程的方式setter对应的参数,也可以通过配置的方式实现,比如:
    spring.main.web-environment=false
    spring.main.banner-mode=off
    使用的前缀是spring.main.*

    4. Embedded servlet containers

    4.1 Add a Servlet, Filter or Listener to an application

    有两种方式:1.把它们作为spring bean; 2.使用@ServletComponentScan,以及Servlet3.0标准注解配置
    具体实现,参考 03 Spring Boot Features.md

    4.2 Change the HTTP port

    server.port 配置端口,
    server.port=-1 关闭端口
    server.port=0 随机空闲端口
    在程序运行中,需要访问使用的什么端口,可以使用@LocalServerPort,参考文档 Discover the HTTP port at runtime

    4.3 Configure Access Logging (配置Servlet容器的访问日志)

    server.tomcat.basedir=my-tomcat
    server.tomcat.accesslog.enabled=true
    server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms)
    参考文档 Access Log Valve
    logs 放在了tomcat base 目录下面,上面的例子中: my-tomcat/logs

    4.4 Use behind a front-end proxy server

    server.use-forward-headers
    详细文档

    4.5 Enable HTTP response compression (开启压缩response)

    HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled viaapplication.properties:
    server.compression.enabled=true
    默认resoponse的最小大小是2048 bytes,只有超过这个大小才会被压缩;可以通过server.compression.min-response-size配置这个大小。
    默认情况去,只会压缩以下类型的响应:
    text/html
    text/xml
    text/plain
    text/css
    能通过server.compression.mime-types配置

    5. Spring MVC

    5.1 Handling Multipart File Uploads

    spring.http.multipart.max-file-size 配置允许上传文件的最大值,如果你想要不限制大小,配置为 -1
    See the MultipartAutoConfiguration source for more details.

    5.2 Customize ViewResolvers

    spring mvc 已经提供了很多ViewResolver的实现类,可以根据自己的需求选择。DispatcherServlet在启动的时候会从ApplicationContext中找出所有的ViewResolver,然后使用每一个都尝试一次,直到找到结果。
    如果自己实现一个ViewResolver, 直接放到ApplicationContext容器中,spring-boot就能使用。
    WebMvcAutoConfiguration已经自动添加了下面的ViewResolvers在你的context中了:
    An InternalResourceViewResolver with bean id ‘defaultViewResolver’. This one locates physical resources that can be rendered using the DefaultServlet(e.g. static resources and JSP pages if you are using those). It applies a prefix and a suffix to the view name and then looks for a physical resource with that path in the servlet context (defaults are both empty, but accessible for external configuration viaspring.mvc.view.prefix and spring.mvc.view.suffix). It can be overridden by providing a bean of the same type.
    A BeanNameViewResolver with id ‘beanNameViewResolver’. This is a useful member of the view resolver chain and will pick up any beans with the same name as the View being resolved. It shouldn’t be necessary to override or replace it.
    A ContentNegotiatingViewResolver with id ‘viewResolver’ is only added if there are actually beans of type View present. This is a ‘master’ resolver, delegating to all the others and attempting to find a match to the ‘Accept’ HTTP header sent by the client. There is a useful blog aboutContentNegotiatingViewResolverthat you might like to study to learn more, and also look at the source code for detail. You can switch off the auto-configured ContentNegotiatingViewResolver by defining a bean named ‘viewResolver’.
    If you use Thymeleaf you will also have a ThymeleafViewResolver with id ‘thymeleafViewResolver’. It looks for resources by surrounding the view name with a prefix and suffix (externalized tospring.thymeleaf.prefix and spring.thymeleaf.suffix, defaults ‘classpath:/templates/’ and ‘.html’ respectively). It can be overridden by providing a bean of the same name.
    If you use FreeMarker you will also have a FreeMarkerViewResolver with id ‘freeMarkerViewResolver’. It looks for resources in a loader path (externalized tospring.freemarker.templateLoaderPath, default ‘classpath:/templates/’) by surrounding the view name with a prefix and suffix (externalized tospring.freemarker.prefix and spring.freemarker.suffix, with empty and ‘.ftl’ defaults respectively). It can be overridden by providing a bean of the same name.
    If you use Groovy templates (actually if groovy-templates is on your classpath) you will also have aGroovyMarkupViewResolver with id ‘groovyMarkupViewResolver’. It looks for resources in a loader path by surrounding the view name with a prefix and suffix (externalized to spring.groovy.template.prefix andspring.groovy.template.suffix, defaults ‘classpath:/templates/’ and ‘.tpl’ respectively). It can be overridden by providing a bean of the same name.
    If you use Velocity you will also have a VelocityViewResolver with id ‘velocityViewResolver’. It looks for resources in a loader path (externalized to spring.velocity.resourceLoaderPath, default ‘classpath:/templates/’) by surrounding the view name with a prefix and suffix (externalized tospring.velocity.prefix and spring.velocity.suffix, with empty and ‘.vm’ defaults respectively). It can be overridden by providing a bean of the same name.

    6. Logging

    73. Logging

    7. Database initialization

    7.1 Initialize a database using JPA

    JPA has features for DDL generation, and these can be set up to run on startup against the database. This is controlled through two external properties:
    spring.jpa.generate-ddl (boolean) switches the feature on and off and is vendor independent.
    spring.jpa.hibernate.ddl-auto (enum) is a Hibernate feature that controls the behavior in a more fine-grained way. See below for more detail.

    7.2 Initialize a database using Hibernate

    spring.jpa.hibernate.ddl-auto 可选的值:none, validate, update, create, create-drop
    spring-boot会自动选择使用哪种,如果你使用的是内嵌的数据库,那么配置create-drop,否则使用none.
    当ddl-auto使用的是create or create-drop,如果在classpath的根目录中有一个文件import.sql,那么在应用启动的时候会被执行

    7.3 Initialize a database using Spring JDBC

    Spring JDBC has a DataSource initializer feature. Spring boot在启动的时候,默认去classpath根目录下加载schema.sql and data.sql。除此之外,spring boot还能加载schema-${platform}.sql and data-${platform}.sql,这里的platform可以通过spring.datasource.platform参数配置,eg: 你可以配置成不同的数据库,hsqldb, h2, oracle, mysql, postgresql etc.
    也通过自己配置文件的位置,spring.datasource.schema and spring.datasource.data
    也可以禁用执行初始化,spring.datasource.initialize=false
    spring.datasource.continue-on-error 在初始化数据库时,遇到错误是否继续,默认false
    The end

    相关文章

      网友评论

        本文标题:springboot 06 ‘How-to’ guides

        本文链接:https://www.haomeiwen.com/subject/afyaqftx.html