zoukankan      html  css  js  c++  java
  • springboot

    Spring boot

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

    从最根本上来讲,Spring Boot就是一些库的集合,它能够被任意项目的构建系统所使用。简便起见,该框架也提供了命令行界面,它可以用来运行和测试Boot应用。框架的发布版本,包括集成的CLI(命令行界面),可以在Spring仓库中手动下载和安装。一种更为简便的方式是使用Groovy环境管理器(Groovy enVironment Manager,GVM),它会处理Boot版本的安装和管理。Boot及其CLI可以通过GVM的命令行gvm install springboot进行安装。

    Eclipse 依赖tomcat时附加:

    <!--tomcat-->

            <dependency>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-starter-tomcat</artifactId>

                <scope>provided</scope>

            </dependency>

            <dependency>

                <groupId>org.apache.tomcat.embed</groupId>

                <artifactId>tomcat-embed-jasper</artifactId>

                <scope>provided</scope>

            </dependency>

    Idea 依赖tomcat时附加:provided在idea中不能被依赖bug

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    Springboot 依赖jpa时注意点:

    .properties配置文件:

    ########################################################
    ### Java Persistence Api u81EAu52A8u8FDBu884Cu5EFAu8868
    ########################################################
    # Specify the DBMS
    spring.jpa.database = MYSQL
    # Show or not log for each sql query
    spring.jpa.show-sql = true
    # Hibernate ddl auto (create, create-drop, update)
    spring.jpa.hibernate.ddl-auto = update
    # Naming strategy
    spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
    # stripped before adding them to the entity manager)
    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

    实体类自动生成数据表:注意Entity和Id和GeneratedValue导包问题。

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import java.io.Serializable;

    @Entity
    public class DemoInfo implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue
        private long id;
        private String name;
        private String pwd;

    导错包会出现以下错误:

     

    Maven 依赖

    Parent 父类

    在pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么staterpoms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。

    <parent>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-parent</artifactId>

       <version>1.3.3.RELEASE</version>

    </parent>

    web依赖:

    <dependencies>

        <dependency>

              <groupId>org.springframework.boot</groupId>

              <artifactId>spring-boot-starter-web</artifactId>

          </dependency>

      </dependencies>

    如果直接maven启动添加plugin

    <build>
        <plugins>
               <plugin>
                   <groupId>org.springframework.boot</groupId>
                   <artifactId>spring-boot-maven-plugin </artifactId>
              </plugin>
          </plugins>
      </build>

    Mysql依赖:

    <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-Java</artifactId>

    </dependency>

    Redis 依赖:

    <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-redis</artifactId>

    </dependency>

    Mybatis依赖:

    <!--  spring-boot mybatis依赖:
           请不要使用1.0.0版本,因为还不支持拦截器插件     -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>

    Hibernate jpa依赖:

    <dependency>

               <groupId>org.springframework.boot</groupId>

               <artifactId>spring-boot-starter-data-jpa</artifactId>

    </dependency>

    MyBatis分页依赖:

    <!--
        MyBatis提供了拦截器接口,我们可以实现自己的拦截器,
        将其作为一个plugin装入到SqlSessionFactory中。
       Github上有位开发者写了一个分页插件,我觉得使用起来还可以,挺方便的。
       Github项目地址: https://github.com/pagehelper/Mybatis-PageHelper
     -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>4.1.0</version>
    </dependency>

    Jdk依赖:

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    Aop依赖:

    <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-aop</artifactId>

    </dependency>

    Mail邮件依赖:

    <!-- 发送邮件. -->

    <dependency> 

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-mail</artifactId>

    </dependency> 

    Test 依赖:<scope>test</scope>在idea中不需要

    <!-- 单元测试. -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        //<scope>test</scope>
    </dependency>

    Lo4fj 日志依赖:

     <!-- log4j. -->

            <dependency> 

               <groupId>org.springframework.boot</groupId>

               <artifactId>spring-boot-starter-log4j</artifactId>

            </dependency>

    Thymeleaf 依赖:

    <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-thymeleaf</artifactId>

    </dependency>

    Mongodb 依赖:

    <!-- 增加mongodb支持 -->

        <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-data-mongodb</artifactId>

        </dependency>

    RebbitMQ 依赖:

    <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-amqp</artifactId>

        </dependency>

    ActiveMQ 依赖:

    这里是引入了activemq的依赖,在这里需要注意下spring boot的版本是1.4.0之前的大部分的例子都是1.3.3的,这里必须是1.4+不然是不支持activemq。

    <!-- activemq support -->

        <dependency>

               <groupId>org.springframework.boot</groupId>

               <artifactId>spring-boot-starter-activemq</artifactId>

        </dependency>

    注解说明:

    1:@RestController

    Spring4 的新注解:注解本身使用@Controller和@ResponseBody注解。使用了这个注解的类会被看作一个controller-使用@RequestMapping的方法有一个默认的@ResponseBody注解。 

    2:@SpringBootApplication

    由于大量项目都会在主要的配置类上添加@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解。因此Spring Boot提供了@SpringBootApplication注解,该注解可以替代上面三个注解(使用Spring注解继承实现)。

    3:@EnableAutoConfiguration

    Spring Boot建议只有一个带有该注解的类。

    @EnableAutoConfiguration作用:Spring Boot会自动根据你jar包的依赖来自动配置项目。例如当你项目下面有HSQLDB的依赖时,Spring Boot会创建默认的内存数据库的数据源DataSource,如果你自己创建了DataSource,Spring Boot就不会创建默认的DataSource。

    4:@ComponentScan

    表示将该类自动发现(扫描)并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Service,@Repository等注解的类。

    5:@Configuration

    相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。

    6:@Import

    用来导入其他配置类。

    7:@ImportResource

    用来加载xml配置文件。

    8:@Repository

    使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。

    9:@Bean

    用@Bean标注方法等价于XML中配置的bean。

    10:@Qualifier

    @Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:

    @Autowired

        @Qualifier(value = "demoInfoService") 

        private DemoInfoService demoInfoService;

    11:@Inject

    等价于默认的@Autowired,只是没有required属性

    12:@ResponseBody

    该注解修饰的函数,会将结果直接填充到HTTP的响应体中,一般用于构建RESTful的api,该注解一般会配合@RequestMapping一起使用。

    @RequestMapping("/test")

        @ResponseBody

        public String test(){

           return"ok";

        }

    13:@Controller

    用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。

    @Controller

    @RequestMapping("/demoInfo")

    publicclass DemoController {

        @Autowired

        private DemoInfoService demoInfoService;

       

        @RequestMapping("/hello")

        public String hello(Map<String,Object> map){

           System.out.println("DemoController.hello()");

           map.put("hello","from TemplateController.helloHtml");

           //会使用hello.html或者hello.ftl模板进行渲染显示.

           return"/hello";

        }

    }

    14:@ConfigurationProperties

    Properties代码

    1. wisely2.name=wyf2  
    2. wisely2.gender=male2 

    自定义配置文件名:

    1. @ConfigurationProperties(prefix = "wisely2")  
    2. public class Wisely2Settings {  
    3.     private String name;  
    4.     private String gender;  
    5.     public String getName() {  
    6.         return name;  
    7.     }  
    8.     public void setName(String name) {  
    9.         this.name = name;  
    10. 10.     }  
    11. 11.     public String getGender() {  
    12. 12.         return gender;  
    13. 13.     }  
    14. 14.     public void setGender(String gender) {  
    15. 15.         this.gender = gender;  
    16. 16.     }  
    17. 17.   

    18. }

    15:@EnableConfigurationProperties

    自动映射一个POJO到Spring Boot配置文件(默认是application.properties文件)的属性集。

    16:@ ConfigurationProperties

    注释将POJO关联到指定前缀的每一个属性。例如,spring.data.mongodb.port属性将映射到这个类的端口属性。

    强烈建议Spring Boot开发者使用这种方式来删除与配置属性相关的瓶颈代码。

    @ConfigurationProperties(prefix = "spring.data.mongodb")

    public class MongoProperties {

        private String host;

        private int port = DBPort.PORT;

        private String uri = "mongodb://localhost/test";

        private String database;

        // ... getters/ setters omitted

    }

    启动类:

    1:例如main 启动类:Applicatio.java 

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }:

    2:通过java代码更改启动端口:

    @RestController
    @SpringBootApplication
    public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer{
        @RequestMapping("/")
        public String hello(){
            return "hello word";
        }

        public static void main(String[] args) {
            SpringApplication.run(Application.class,args);
        }

        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(8081);
        }

        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
            return builder.sources(Application.class);
        }
    }

    .yml或.properties配置属性

    默认文件名字:application.properties路径是src/main/resources下

    1:配置文件属性:

    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视图的后缀.
    • spring.messages.basename
      指定message的basename,多个以逗号分隔,如果不加包名的话,默认从classpath路径开始,默认: messages
    • spring.messages.cache-seconds
      设定加载的资源文件缓存失效时间,-1的话为永不过期,默认为-1
    • spring.messages.encoding
      设定Message bundles的编码,默认: UTF-8
    • 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
    • spring.view.prefix
      设定mvc视图的前缀.
    • spring.view.suffix
      设定mvc视图的后缀.
    • 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.enabled
      是否开启文件上传支持,默认为true
    • multipart.file-size-threshold
      设定文件写入磁盘的阈值,单位为MB或KB,默认为0
    • multipart.location
      指定文件上传路径.
    • multipart.max-file-size
      指定文件大小最大值,默认1MB
    • multipart.max-request-size
      指定每次请求的最大值,默认为10MB
    • 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
      指定使用模板的视图列表.
    • 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
      设定需要解析的视图名称.
    • 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
      指定使用模板的视图名,多个以逗号分隔.
    • 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
      指定要使用模板的视图名.
    • 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
      指定要使用模板的视图名称.
    • 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
    • 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.
    • spring.jersey.filter.order
      指定Jersey filter的order,默认为: 0
    • spring.jersey.init
      指定传递给Jersey的初始化参数.
    • spring.jersey.type
      指定Jersey的集成类型,可以是servlet或者filter.

    messages

    mobile

    view

    resource

    multipart

    freemarker

    velocity

    thymeleaf

    mustcache

    groovy模板

    http

    json

    jersey

    reids

    # REDIS (RedisProperties)

    #spring.redis.database=0

    spring.redis.host=127.0.0.1

    spring.redis.password=

    spring.redis.port=6379

    spring.redis.pool.max-idle=100

    spring.redis.pool.min-idle=1

    spring.redis.pool.max-active=1000

    spring.redis.pool.max-wait=-1

    datasource

    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=

    jpa

    spring.jpa.database = MYSQL

    # Show or not log for each sql query

    spring.jpa.show-sql = true

    # Hibernate ddl auto (create, create-drop, update)

    spring.jpa.hibernate.ddl-auto = update

    # Naming strategy

    #[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]

    spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

    DefaultNamingStrategy这个直接映射,不会做过多的处理(前提没有设置@Table,@Column等属性的时候)。

    ImprovedNamingStrategy  表名,字段为小写,当有大写字母的时候会转换为分隔符号“_”。

    # stripped before adding them to the entity manager)

    spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect

    tomcat

    #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 totmp)

    #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 URLdecoding

    常用tomcat配置:

    # tomcat最大线程数,默认为200

    server.tomcat.max-threads=800

    # tomcat的URI编码

    server.tomcat.uri-encoding=UTF-8

    # 存放Tomcat的日志、Dump等文件的临时文件夹,默认为系统的tmp文件夹(如:C:UsersAngelAppDataLocalTemp)

    server.tomcat.basedir=D:/springboot-tomcat-tmp

    # 打开Tomcat的Access日志,并可以设置日志格式的方法:

    #server.tomcat.access-log-enabled=true

    #server.tomcat.access-log-pattern=

    # accesslog目录,默认在basedir/logs

    #server.tomcat.accesslog.directory=

    # 日志文件目录

    logging.path=H:/springboot-tomcat-tmp

    # 日志文件名称,默认为spring.log

    logging.file=myapp.log

    Server

    #项目contextPath,一般在正式发布版本中,我们不配置

    server.context-path=/springboot

    # 错误页:指定发生错误时,跳转的URL。请查看BasicErrorController。

    server.error.path=/error

    # 服务端口,默认为8080

    server.port=8080

    # session最大超时时间(分钟),默认为30

    server.session-timeout=60

    # 该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败,只有特殊需求的情况下才配置

    # server.address=192.168.16.11

    Aop

    springboot默认的是Java的动态代理模式,我们只需要修改为CGLIB动态代码模式即可,只需要在application.properties加入如下配置:例如我们在service写接口,在实现类实现接口。(没有特殊用法不改)

    spring.aop.proxy-target-class=true

    MongoDb

    spring.data.mongodb.authentication-database= # Authentication database name.

    spring.data.mongodb.database=test # Database name.

    spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.

    spring.data.mongodb.grid-fs-database= # GridFS database name.

    spring.data.mongodb.host=localhost # Mongo server host.

    spring.data.mongodb.password= # Login password of the mongo server.

    spring.data.mongodb.port=27017 # Mongo server port.

    spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.

    spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored.

    spring.data.mongodb.username= # Login user of the mongo server.

    RebbitMQ

    # RABBIT (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= 

    ActiveMq

    # ACTIVEMQ (ActiveMQProperties)

    spring.activemq.broker-url= # URL of the ActiveMQ broker. Auto-generated by default. For instance `tcp://localhost:61616`

    spring.activemq.in-memory=true # Specify if the default broker URL should be in memory. Ignored if an explicit broker has been specified.

    spring.activemq.password= # Login password of the broker.

    spring.activemq.user= # Login user of the broker.

    spring.activemq.packages.trust-all=false # Trust all packages.

    spring.activemq.packages.trusted= # Comma-separated list of specific packages to trust (when not trusting all packages).

    spring.activemq.pool.configuration.*= # See PooledConnectionFactory.

    spring.activemq.pool.enabled=false # Whether a PooledConnectionFactory should be created instead of a regular ConnectionFactory.

    spring.activemq.pool.expiry-timeout=0 # Connection expiration timeout in milliseconds.

    spring.activemq.pool.idle-timeout=30000 # Connection idle timeout in milliseconds.

    spring.activemq.pool.max-connections=1 # Maximum number of pooled connections.

    2:可以进行自定义配置类:

    1:例如:Properties代码

    1. wisely2.name=wyf2  
    2. wisely2.gender=male2

    定义配置类:Java代码

    1. @ConfigurationProperties(prefix = "wisely2")  
    2. public class Wisely2Settings {  
    3.     private String name;  
    4.     private String gender;  
    5.     public String getName() {  
    6.         return name;  
    7.     }  
    8.     public void setName(String name) {  
    9.         this.name = name;  
    10. 10.     }  
    11. 11.     public String getGender() {  
    12. 12.         return gender;  
    13. 13.     }  
    14. 14.     public void setGender(String gender) {  
    15. 15.         this.gender = gender;  
    16. 16.     }  
    17. 17.   

    18. }  

    自定义配置文件名:

    1:例如:Properties代码

    1. wisely2.name=wyf2 
    2. wisely2.gender=male2

    2:需定义如下配置类:Java代码

    1. @ConfigurationProperties(prefix = "wisely",locations = "classpath:config/wisely.properties")  
    2. public class WiselySettings {  
    3.     private String name;  
    4.     private String gender;  
    5.     public String getName() {  
    6.         return name;  
    7.     }  
    8.     public void setName(String name) {  
    9.         this.name = name;  
    10. 10.     }  
    11. 11.     public String getGender() {  
    12. 12.         return gender;  
    13. 13.     }  
    14. 14.     public void setGender(String gender) {  
    15. 15.         this.gender = gender;  
    16. 16.     }  
    17. 17.   

    18. }  

    最后在spring Boot入口类加上@EnableConfigurationProperties:Java代码

    1. @SpringBootApplication  
    2. @EnableConfigurationProperties({WiselySettings.class,Wisely2Settings.class})  
    3. public class DemoApplication {  
    4.   
    5.     public static void main(String[] args) {  
    6.         SpringApplication.run(DemoApplication.class, args);  
    7.     }  
    8. }  

    静态资源文件:

    spring Boot 默认为我们提供了静态资源处理,使用WebMvcAutoConfiguration 中的配置各种属性。建议大家使用SpringBoot的默认配置方式,如果需要特殊处理的再通过配置进行修改。

    如果想要自己完全控制WebMVC,就需要在@Configuration注解的配置类上增加@EnableWebMvc(@SpringBootApplication注解的程序入口类已经包含@Configuration),增加该注解以后WebMvcAutoConfiguration中配置就不会生效,你需要自己来配置需要的每一项。这种情况下的配置还是要多看一下WebMvcAutoConfiguration类。

    控制台输出:

    2016-01-08 09:29:30.437  INFO 24932 ---[           main]o.s.w.s.handler.SimpleUrlHandlerMapping  : MappedURLpath[/**/favicon.ico]ont

    默认路径:

    其中默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources) 
    其中默认配置的 /webjars/** 映射到 classpath:/META-INF/resources/webjars/ 
    PS:上面的 static、public、resources 等目录都在 classpath: 下面(如 src/main/resources/static)。

    自定义资源映射(工程目录下):

    以增加/myres/* 映射到 classpath:/myres/* 为例的代码处理为: 

    @Configuration

    public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

        @Override

        public voidaddResourceHandlers(ResourceHandlerRegistry registry) {

            registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");

            super.addResourceHandlers(registry);

        }

    }

    使用外部目录

    通过配置文件配置:

    spring.mvc.static-path-pattern=

    # 默认值为classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

    spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开,

    使用spring.mvc.static-path-pattern 可以重新定义pattern,如修改为 /myres/** ,则访问static 等目录下的fengjing.jpg文件应该为http://localhost:8080/myres/fengjing.jpg ,修改之前为 http://localhost:8080/fengjing.jpg

    使用 spring.resources.static-locations 可以重新定义 pattern 所指向的路径,支持 classpath: 和 file: (上面已经做过说明)

    注意 spring.mvc.static-path-pattern 只可以定义一个,目前不支持多个逗号分割的方式。

    定时任务:

    @Configuration

    @EnableScheduling

    Public class SchedulingConfig {

        @Scheduled(cron = "0/20 * * * * ?") // 每20秒执行一次

        publicvoid scheduler() {

            System.out.println(">>>>>>>>> SchedulingConfig.scheduler()");

        }

    }

    Springboot启动select、Filter、Listener

    在springBootApplication中加上@ServletComponentScan注解Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。

    例如:

    @WebServlet(urlPatterns="/myServlet2/*",description="Servlet的说明")

    public class MyServlet2 extends HttpServlet{

           private static finallong serialVersionUID = 1L;

           @Override

        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {

           System.out.println(">>>>>>>>>>doGet()<<<<<<<<<<<");

            doPost(req, resp);

        }

        @Override

        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {

           System.out.println(">>>>>>>>>>doPost()<<<<<<<<<<<");

            resp.setContentType("text/html"); 

            PrintWriter out =resp.getWriter(); 

           out.println("<html>"); 

           out.println("<head>"); 

           out.println("<title>Hello World</title>"); 

           out.println("</head>"); 

            out.println("<body>"); 

           out.println("<h1>这是:myServlet2</h1>"); 

           out.println("</body>"); 

           out.println("</html>");

        }

    }

    SpringBootApplication中:

    @SpringBootApplication

    @ServletComponentScan//这个就是扫描相应的Servlet包;

    public class SpringBootSampleApplication {

     

        public static void main(String[]args) {

            SpringApplication.run(SpringBootSampleApplication.class, args);

        }

    }

    SpringBoot拦截器:

    1:实现HandlerInterceptor接口

    Public class MyInterceptor1 implements HandlerInterceptor {

        @Override

        Public boolean preHandle(HttpServletRequestrequest, HttpServletResponse response, Object handler) throws Exception {

            System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");

            Return true;// 只有返回true才会继续向下执行,返回false取消当前请求

        }

        @Override

        Public void postHandle(HttpServletRequestrequest, HttpServletResponse response, Object handler, ModelAndViewmodelAndView) throws Exception {

            System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");

        }

        @Override

        Public void afterCompletion(HttpServletRequestrequest, HttpServletResponse response, Object handler, Exception ex)

                throws Exception {

            System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");

        }

    }

    2:继承WebMvcConfigurerAdapter

    @Configuration

    public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {

        @Override

        Public void addInterceptors(InterceptorRegistryregistry) {

            // 多个拦截器组成一个拦截器链

            // addPathPatterns 用于添加拦截规则

            // excludePathPatterns 用户排除拦截

            registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");

            registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");

            super.addInterceptors(registry);

        }

    }

    启动时加载:

    spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。

    在多个启动加载时,可以用@Order(value=2)自定义执行顺序。

    @Component

    //@Order(value=2)  可以用这个注解来定义执行顺序

    public class MyStartupRunner1 implements CommandLineRunner {

        @Override

        Public void run(String...args) throws Exception {

            System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");

        }

    }

    Springboot使用自定义properties

    1:在application.properties中配置自定义配置属性时,想要注入自定义的配置类

     

    application.properties中:

    1.     wisely2.name=wyf2  

    2.     wisely2.gender=male2  

    自定义配置类:

    @ConfigurationProperties(prefix = "wisely2")  

    2.     public class Wisely2Settings {  

    3.         private String name;  

    4.         private String gender;  

    Get..set..

    2:自定义配置文件名

    wisely.properties

    1.     wisely.name=wangyunfei  

    2.     wisely.gender=male  

    需定义如下配置类:

    @ConfigurationProperties(prefix = "wisely",locations = "classpath:config/wisely.properties")  

    2.     public class WiselySettings {  

    3.         private String name;  

    4.         private String gender;  

    Get…set…

     

    最后在Springboot 入口类加上@EnableConfigurationProperties

    1.     @SpringBootApplication  

    2.     @EnableConfigurationProperties({WiselySettings.class,Wisely2Settings.class})  

    3.     public class DemoApplication {  

    4.       

    5.         public static void main(String[] args) {  

    6.             SpringApplication.run(DemoApplication.class, args);  

    7.         }  

    8.     }  

    Springboot自动扫描不同包

    cn.kfit;包下的

    @Configuration

    public class MyCommandLineRunner2 implementsCommandLineRunner {

           @Override

           public void run(String... args) throws Exception {

                  System.out.println("MyCommandLineRunner2.run()");

           }

    }

    cn.kfit;包下的:

    @Configuration

    public class MyCommandLineRunner1 implementsCommandLineRunner {

           @Override

           public void run(String... args) throws Exception {

                  System.out.println("MyCommandLineRunner1.run()");

           }

    }

    @ComponentScan(basePackages={"cn.kfit","org.kfit"})

    这时候你会发现,在App.java同包下的都没有被扫描了,所以如果也希望App.java包下的也同时被扫描的话,那么在进行指定包扫描的时候一定要进行指定配置:

    @ComponentScan(basePackages={"cn.kfit","org.kfit","com.kfit"})

    spring boot junit单元测试

    1:加入maven依赖:

    <dependency>

           <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

           <scope>test</scope>

     </dependency>

    2:测试service

    @Service

    public class HelloService {

           public String getName(){

                  return "hello";

           }

    }

    3).编写测试类:

    //// SpringJUnit支持,由此引入Spring-Test框架支持!

    @RunWith(SpringJUnit4ClassRunner.class)

    //// 指定我们SpringBoot工程的Application启动类

    @SpringApplicationConfiguration(classes = App.class)

    ///由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。

    @WebAppConfiguration

    public class HelloServiceTest {

           @Resource

           private HelloService helloService;

           @Test

           public void testGetName(){

                  Assert.assertEquals("hello",helloService.getName());

           }

    }

    Junit注解介绍:

    //在所有测试方法前执行一次,一般在其中写上整体初始化的代码 
    @BeforeClass

    //在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码 
    @AfterClass

    //在每个测试方法前执行,一般用来初始化方法(比如我们在测试别的方法时,类中与其他测试方法共享的值已经被改变,为了保证测试结果的有效性,我们会在@Before注解的方法中重置数据) 
    @Before

    //在每个测试方法后执行,在方法执行完成后要做的事情 
    @After

    // 测试方法执行超过1000毫秒后算超时,测试将失败 
    @Test(timeout = 1000)

    // 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败 
    @Test(expected = Exception.class)

    // 执行测试时将忽略掉此方法,如果用于修饰类,则忽略整个类 
    @Ignore(“not ready yet”) 
    @Test

    @RunWith 
    在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。 
    如果我们只是简单的做普通Java测试,不涉及SpringWeb项目,你可以省略@RunWith注解,这样系统会自动使用默认Runner来运行你的代码。

    文件上传:

    1:在controller层中加入MultipartFile

    @RequestMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file")MultipartFile file){
        if(!file.isEmpty()){
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            }catch(FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败,"+e.getMessage();
            }catch (IOException e) {
                e.printStackTrace();
                return "上传失败,"+e.getMessage();
            }
                return "上传成功";
        }else {
            return "上传失败,因为文件是空的.";
        }
    }

    2:在html中指定上传格式multipart/form-data

    <html>
    <head>
        <title>hello</title>
    </head>
    <body>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <p>文件:<input type="file" name="file"/></p>
            <p><input type="submit" value="上传"/></p>
        </form>
    </body>
    </html>

    3.    上传文件进行限制

    1. @Bean 
    2.    public MultipartConfigElement multipartConfigElement() { 
    3.         MultipartConfigFactory factory = newMultipartConfigFactory();
    4.         //// 设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了;
    5.         factory.setMaxFileSize("128KB"); //KB,MB
    6.         /// 设置总上传数据总大小
    7.         factory.setMaxRequestSize("256KB"); 
    8.         //Sets the directory location wherefiles will be stored.
    9.         //factory.setLocation("路径地址");
    10.         return factory.createMultipartConfig(); 
    11.     } 
    12. /**
    13.         * 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile
    14.         * @param request
    15.         * @return
    16.         */
    17.        @RequestMapping(value="/batch/upload", method=RequestMethod.POST
    18.    public @ResponseBody 
    19.    String handleFileUpload(HttpServletRequest request){ 
    20.         List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file"); 
    21.         MultipartFile file = null;
    22.         BufferedOutputStream stream = null;
    23.         for (int i =0; i< files.size(); ++i) { 
    24.             file = files.get(i); 
    25.             if (!file.isEmpty()) { 
    26.                 try { 
    27.                     byte[] bytes = file.getBytes(); 
    28.                     stream = 
    29.                             newBufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename()))); 
    30.                     stream.write(bytes); 
    31.                     stream.close(); 
    32.                 } catch (Exception e) { 
    33.                        stream =  null;
    34.                     return "You failed to upload " + i + " =>" + e.getMessage(); 
    35.                 } 
    36.             } else { 
    37.                 return "You failed to upload " + i + " becausethe file was empty."; 
    38.             } 
    39.         } 
    40.         return "upload successful"; 
    41.     } 

    3.    多文件上传实现:

     

    引用xml文件:

    ImportResource有两种引用方式classpath和file

    classpath路径:locations={"classpath:application-bean1.xml","classpath:application-bean2.xml"}

     file路径:

    locations= {"file:d:/test/application-bean1.xml"};

    在Springboot入口同级目录下创建引用:

    @Configuration
    @ImportResource(locations = {"classpath:application-bean.xml"})
    public class ConfigClass {

    }

    Xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--无法扫描的service-->
        <bean id="helloService" class="cn.bagtree.service.HelloService"/>
    </beans>

    Springboot 启动器:

    Spring Boot应用启动器基本的一共有N(现知道的是44)种:具体如下

    1)spring-boot-starter这是Spring Boot的核心启动器,包含了自动配置、日志和YAML。

    2)spring-boot-starter-actuator帮助监控和管理应用。

    3)spring-boot-starter-amqp通过spring-rabbit来支持AMQP协议(Advanced Message Queuing Protocol)。

    4)spring-boot-starter-aop支持面向方面的编程即AOP,包括spring-aop和AspectJ。

    5)spring-boot-starter-artemis通过Apache Artemis支持JMS的API(Java Message Service API)。

    6)spring-boot-starter-batc支持Spring Batch,包括HSQLDB数据库。

    7)spring-boot-starter-cache支持Spring的Cache抽象。

    8)spring-boot-starter-cloud-connectors支持Spring Cloud Connectors,简化了在像Cloud Foundry或Heroku这样的云平台上连接服务。

    9)spring-boot-starter-data-elasticsearch支持ElasticSearch搜索和分析引擎,包括spring-data-elasticsearch。

    10)spring-boot-starter-data-gemfire支持GemFire分布式数据存储,包spring-data-gemfire。

    11)spring-boot-starter-data-jpa支持JPA(Java Persistence API),包括spring-data-jpa、spring-orm、Hibernate。

    12)spring-boot-starter-data-mongodb支持MongoDB数据,包括spring-data-mongodb。

    13)spring-boot-starter-data-rest通过spring-data-rest-webmvc,支持通过REST暴露Spring Data数据仓库。

    14)spring-boot-starter-data-solr支持Apache Solr搜索平台,包括spring-data-solr。

    15)spring-boot-starter-freemarker支持FreeMarker模板引擎。

    16)spring-boot-starter-groovy-templates支持Groovy模板引擎。

    17)spring-boot-starter-hateoas通过spring-hateoas支持基于HATEOAS的RESTful Web服务。

    18)spring-boot-starter-hornetq通过HornetQ支持JMS。

    19)spring-boot-starter-integration支持通用的spring-integration模块。

    20)spring-boot-starter-jdbc支持JDBC数据库。

    21)spring-boot-starter-jersey支持Jersey RESTful Web服务框架。

    22)spring-boot-starter-jta-atomikos通过Atomikos支持JTA分布式事务处理。

    23)spring-boot-starter-jta-bitronix通过Bitronix支持JTA分布式事务处理。

    24)spring-boot-starter-mail支持javax.mail模块。

    25)spring-boot-starter-mobile支持spring-mobile。

    26)spring-boot-starter-mustache支持Mustache模板引擎。

    27)spring-boot-starter-redis支持Redis键值存储数据库,包括spring-redis。

    28)spring-boot-starter-security支持spring-security。

    29)spring-boot-starter-social-facebook支持spring-social-facebook

    30)spring-boot-starter-social-linkedin支持pring-social-linkedin

    31)spring-boot-starter-social-twitter支持pring-social-twitter

    32)spring-boot-starter-test支持常规的测试依赖,包括JUnit、Hamcrest、Mockito以及spring-test模块。

    33)spring-boot-starter-thymeleaf支持Thymeleaf模板引擎,包括与Spring的集成。

    34)spring-boot-starter-velocity支持Velocity模板引擎。

    35)spring-boot-starter-web 支持全栈式Web开发,包括Tomcat和spring-webmvc。 

    36)spring-boot-starter-websocket支持WebSocket开发。

    37)spring-boot-starter-ws支持Spring Web Services。Spring Boot应用启动器面向生产环境的还有2种,具体如下:

    1)spring-boot-starter-actuator增加了面向产品上线相关的功能,比如测量和监控。

    2)spring-boot-starter-remote-shell增加了远程ssh shell的支持。

    最后,Spring Boot应用启动器还有一些替换技术的启动器,具体如下:

    1)spring-boot-starter-jetty引入了Jetty HTTP引擎(用于替换Tomcat)。

    2)spring-boot-starter-log4j支持Log4J日志框架。

    3)spring-boot-starter-logging引入了Spring Boot默认的日志框架Logback。

    4)spring-boot-starter-tomcat引入了Spring Boot默认的HTTP引擎Tomcat。

    5)spring-boot-starter-undertow引入了Undertow HTTP引擎(用于替换Tomcat)。

    SpringBoot集成redis

    核心类:

    @Configuration
    @EnableCaching//启用缓存,这个注解很重要;
    public class RedisCacheConfig extends CachingConfigurerSupport{
        /**
         *
    缓存管理器.
         * @param
    redisTemplate
        
    * @return
        
    */
       
    @Bean
        public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) {
            CacheManager cacheManager = new RedisCacheManager(redisTemplate);
            return cacheManager;
        }


        /**
         * redis
    模板操作类,类似于jdbcTemplate的一个类;
         *
         *
    虽然CacheManager也能获取到Cache对象,但是操作起来没有那么灵活;
        
    *
         *
    这里在扩展下:RedisTemplate这个类不见得很好操作,我们可以在进行扩展一个我们
        
    *
         *
    自己的缓存类,比如:RedisStorage;
         *
         * @param
    factory : 通过Spring进行注入,参数在application.properties进行配置;
        
    * @return
        
    */
       
    @Bean
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
            redisTemplate.setConnectionFactory(factory);

            //key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
            //所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
            //或者JdkSerializationRedisSerializer序列化方式;
    //     RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型不可以会出现异常信息;
    //     redisTemplate.setKeySerializer(redisSerializer);
    //     redisTemplate.setHashKeySerializer(redisSerializer);

            return redisTemplate;
        }

    /**
     *
    自定义key.
     *
    此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。
     
    */
    @Override
    public KeyGenerator keyGenerator() {
        System.out.println("RedisCacheConfig.keyGenerator()");
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                // This will generate a unique key of the class name, the method name
                //and all method parameters appended.
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                System.out.println("keyGenerator=" + sb.toString());
                return sb.toString();
            }
        };
    }

    主要注解:@EnableCaching启用缓存

    实现CachingConfigurer,然后注入需要的cacheManager和keyGenerator;从spring4开始默认的keyGenerator是SimpleKeyGenerator。不想要自定义key值可以不要keyGenerator

    重写RedisTemplate模板,可以添加自己想要的数据

    分布式Session状态保存redis

    1.添加session依赖:

    <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-redis</artifactId>

        </dependency>

      <dependency>

          <groupId>org.springframework.session</groupId>

          <artifactId>spring-session-data-redis</artifactId>

    </dependency>

    2.添加注解:@EnableRedisHttpSession
    如果需要添加失效时间:@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60) //1分钟失效

    3.所有实体类实现Serializable接口

    Springboot日志记录slf4j

    1、在 src/main/resources 下面创建logback.xml (根据不同环境来定义不同的日志输出,那么取名为logback-spring.xml 即可)文件,并按上面讲述的进行配置。 
    或者使用最简单的方法在 application 配置文件中配置。 
    2、在Java代码中创建实例,并在需要输出日志的地方使用。

    logback-spring.xml 文件:

    <?xml version="1.0" encoding="UTF-8"?>

    <configuration>

        <include resource="org/springframework/boot/logging/logback/base.xml" />

        <logger name="org.springframework.web" level="INFO"/>

        <logger name="org.springboot.sample" level="TRACE" />

        <springProfile name="dev">

            <logger name="org.springboot.sample" level="DEBUG" />

        </springProfile>

        <springProfile name="staging">

            <logger name="org.springboot.sample" level="INFO" />

    </springProfile>

    </configuration>

    在代码中引用日志:

    private Logger logger =  LoggerFactory.getLogger(this.getClass());

    也可以配置log4j-spring.properties 自定义格式:
    在引入了log4j依赖之后,只需要在src/main/resources目录下加入log4j-spring.properties配置文件,就可以开始对应用的日志进行配置使用。

    Springboot集成mytatis

    1:在扫描入口加入主要注解:@MapperScan

    @SpringBootApplication
    @MapperScan("com.bagtree.mapper")
    public class App {

        public static void main(String[] args) {
            SpringApplication.run(App.class,args);
        }
    }

    2:写mapper层:

    public interface DemoMapper {
        @Select("select *from Demo where name = #{name}")
        public List<Demo> likeName(String name);

        @Select("select *from Demo where id = #{id}")
        public Demo getById(long id);

        @Select("select name from Demo where id = #{id}")
        public String getNameById(long id);
    }

    分页插件的使用:

    配置属性:

    @Configuration

    public class MyBatisConfiguration {

        @Bean

        public PageHelper pageHelper() {

           System.out.println("MyBatisConfiguration.pageHelper()");

            PageHelper pageHelper = new PageHelper();

            Properties p = new Properties();

            p.setProperty("offsetAsPageNum", "true");

            p.setProperty("rowBoundsWithCount", "true");

            p.setProperty("reasonable", "true");

            pageHelper.setProperties(p);

            return pageHelper;

        }

    }

    查询时设置分页:PageHelper.startPage

    @RequestMapping("/likeName")
    public List<Demo> likeName(String name){
        PageHelper.startPage(1,1);
        return demoService.likeName(name);
    }

    Aop切面日志演示

    实现AOP的切面主要有以下几个要素:

    使用@Aspect注解将一个java类定义为切面类

    使用@Pointcut定义一个切入点,可以是一个规则表达式,比如下例中某个package下的所有函数,也可以是一个注解等。

    根据需要在切入点不同位置的切入内容

    使用@Before在切入点开始处切入内容

    使用@After在切入点结尾处切入内容

    使用@AfterReturning在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)

    使用@Around在切入点前后切入内容,并自己控制何时执行切入点自身的内容

    使用@AfterThrowing用来处理当切入内容部分抛出异常之后的处理逻辑

    /**

     * 实现Web层的日志切面

     * @author Angel(QQ:412887952)

     * @version v.0.1

     */

    @Aspect

    @Component

    @Order(-5)

    public class WebLogAspect {

        private Logger logger =  LoggerFactory.getLogger(this.getClass());

       

        ThreadLocal<Long> startTime = new ThreadLocal<Long>();

       

        /**

         * 定义一个切入点.

         * 解释下:

         * ~ 第一个 * 代表任意修饰符及任意返回值.

         * ~ 第二个 * 任意包名

         * ~ 第三个 * 代表任意方法.

         * ~ 第四个 * 定义在web包或者子包

         * ~ 第五个 * 任意方法

         * ~ .. 匹配任意数量的参数.

         */

         @Pointcut("execution(public * com.kfit.*.web..*.*(..))")

         Public void webLog(){}

         

         @Before("webLog()")

         Public void doBefore(JoinPoint joinPoint){

            startTime.set(System.currentTimeMillis());

           // 接收到请求,记录请求内容

            logger.info("WebLogAspect.doBefore()");

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

             HttpServletRequest request = attributes.getRequest();  

          // 记录下请求内容

            logger.info("URL : " + request.getRequestURL().toString());

            logger.info("HTTP_METHOD : " + request.getMethod());

            logger.info("IP : " + request.getRemoteAddr());

            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() +"." + joinPoint.getSignature().getName());

            logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

           //获取所有参数方法一:

            Enumeration<String> enu=request.getParameterNames(); 

            while(enu.hasMoreElements()){ 

                String paraName=(String)enu.nextElement(); 

                System.out.println(paraName+": "+request.getParameter(paraName)); 

            } 

         }

         @AfterReturning("webLog()")

         Public void  doAfterReturning(JoinPoint joinPoint){

           // 处理完请求,返回内容

            logger.info("WebLogAspect.doAfterReturning()");

            logger.info("耗时(毫秒) : " + (System.currentTimeMillis() - startTime.get()));

         }

    }

    Springboot部署配置:

    更改jetty为启动服务器:

    1:spring boot默认是Tomcat,如果你要选择Jetty,也非常简单,只需要把pom.xml中的tomcat依赖排除,并加入Jetty容器的依赖接口,如下配置:

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

        <!-- 排除默认的tomcat,引入jetty容器. -->

        <exclusions>

          <exclusion>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-tomcat</artifactId>

          </exclusion>

        </exclusions>

     </dependency>

     <!-- jetty 容器. -->

     <dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-jetty</artifactId>

     </dependency>

    2:修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法

    @SpringBootApplication

    publicclass App extends SpringBootServletInitializer{

        @Override

        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

            returnbuilder.sources(this.getClass());

        }

       

        Public static void main(String[] args) {

           SpringApplication.run(App.class, args);

    }

    }

    3:修改pom文件中jar 为 war

    <!-- <packaging>jar</packaging> -->

    <packaging>war</packaging>

    打印springboot启动时加载的bean

    我们只需要稍微调整下就可以获取到ApplicationContext上下文了,在这个类中就可以有很多的方法进行操作了,修改为如下:

    ApplicationContext ctx = SpringApplication.run(ApiCoreApp.class, args);

    第一种情况获取所有的beans:

    ApplicationContext ctx = SpringApplication.run(ApiCoreApp.class, args);

           String[] beanNames =  ctx.getBeanDefinitionNames();

           System.out.println("所以beanNames个数:"+beanNames.length);

           for(String bn:beanNames){

           System.out.println(bn);

    }

    Springboot访问url路径规则

    核心的开发步骤就是两步:

    (1)启动类 extends WebMvcConfigurationSupport

    (2)重写configurePathMatch方法;

    @SpringBootApplication

    public class ApiCoreApp extends WebMvcConfigurationSupport{

       

       

        /**

         * 1、 extends WebMvcConfigurationSupport

         * 2、重写下面方法;

         * setUseSuffixPatternMatch : 设置是否是后缀模式匹配,如“/user”是否匹配/user.*,默认真即匹配;

         * setUseTrailingSlashMatch : 设置是否自动后缀路径模式匹配,如“/user”是否匹配“/user/”,默认真即匹配;

         */

        @Override

        Public void configurePathMatch(PathMatchConfigurer configurer) {

            configurer.setUseSuffixPatternMatch(false)

                       .setUseTrailingSlashMatch(true);

        }

       

        Public static void main(String[] args) {

           SpringApplication.run(ApiCoreApp.class, args);

        }

    }

    Springboot集成MongoDB

    /**

     * 继承自MongoRepository接口,MongoRepository接口包含了常用的CRUD操作,

     * 例如:save、insert、findall等等。我们可以定义自己的查找接口,

     * 例如根据demoInfo的name搜索,具体的DemoInfoRepository接口代码如下:

     * @author Angel --守护天使

     * @version v.0.1

     * @date 2016年8月18日下午3:15:49

     */

    public interface  DemoInfoRepository  extends MongoRepository<DemoInfo, String> {

        DemoInfo findByName(String name);

    }

    Springboot集成RebbitMQ

    @SpringBootApplication

    @EnableScheduling//启用任务调度.

    @RabbitListener(queues="foo")//启用Rabbit队列监听foo key.作用于类下所有方法

    public class App {

        //rabbit操作类;

        @Autowired

        private RabbitTemplate rabbitTemplate;

          

        @Scheduled(fixedDelay=3000)//3s执行1次此方法;

        public void send(){

           rabbitTemplate.convertAndSend("foo","zhang");

        }

       

        @Bean

        public Queue fooQueue(){

           returnnew  Queue("foo");

        }

           

        //接收到消息处理.

        @RabbitHandler

        public void onMessage(@Payload String foo){

           System.out.println(" >>> "+new Date() + ": " + foo);

        }

       

        public static void main(String[] args) {

           SpringApplication.run(App.class, args);

        }

    }

    方法还可以在简化下,将类上的@RabbitListener直接转移到方法上,去掉@RabbitHandler注解,直接为如下:

    //接收到消息处理.

        @RabbitListener(queues = "foo")

        public void onMessage(@Payload String foo){

           System.out.println(" >new>> "+new Date() + ": " + foo);

    }

    Springboot集成ActiveMQ

    1.启动入口:

    @SpringBootApplication

    public class App {

        @Bean

        public Queue queue() {

           return new ActiveMQQueue("sample.queue");

        }

       

        public static void main(String[] args) {

           SpringApplication.run(App.class, args);

        }

    }

    2.消费者

    @Component

    @EnableScheduling

    public class Producer {

       

        @Autowired

        private JmsMessagingTemplate jmsMessagingTemplate;

       

        @Autowired

        private Queue queue;

       

        @Scheduled(fixedDelay=3000)//每3s执行1次

        public void send() {

           this.jmsMessagingTemplate.convertAndSend(this.queue, "hi,activeMQ");

        }

       

    }

    3.监听者

    @Component

    public class Consumer {

        @JmsListener(destination = "sample.queue")

        public void receiveQueue(String text) {

           System.out.println(text);

        }

    }

     

  • 相关阅读:
    IP分类:A,B,C,D,E五类
    Makefile之“=”、":="、“+=”、“?=”
    Makefile之字符串函数
    Makefile之嵌套执行make
    vi中使用“/”查找字符
    Makefile学习之显示命令与出错命令
    【转】Unity中写GLSL(一)—— 简单的diffuse color
    关于编译GITHUB上的工程
    认识了一个新的手机游戏剖析工具- SnapDragon Profiler
    U3D资料收藏
  • 原文地址:https://www.cnblogs.com/maofa/p/6407040.html
Copyright © 2011-2022 走看看