springboot入门(转)

1.Spring的发展

1.1.   Spring1.x 时代

在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换。

1.2.   Spring2.x时代

随着JDK 1.5带来的注解支持,Spring2.x可以使用注解对Bean进行申明和注入,大大的减少了xml配置文件,同时也大大简化了项目的开发。

那么,问题来了,究竟是应该使用xml还是注解呢?

最佳实践:

1、 应用的基本配置用xml,比如:数据源、资源文件等;

2、 业务开发用注解,比如:Service中注入bean等; 

1.3.   Spring3.x到Spring4.x

从Spring3.x开始提供了Java配置方式,使用Java配置方式可以更好的理解你配置的Bean,现在我们就处于这个时代,并且Spring4.x和Spring boot都推荐使用java配置的方式。


2.Spring的Java配置方式

其实从spring3.x就开始推荐使用Java配置的方式了。可以完全替代XML配置。

SpringJava配置会用到的几个注解:@Configuration 和 @Bean和@PropertySource

作用如下:

@Configuration作用于类上,相当于一个xml配置文件

@Bean作用于方法(一个生产指定对象的方法)上,相当于xml配置中的<bean>

@PropertySource指定资源文件所在的路径

2.2.   需求:实现HttpClient的配置

通过Java配置方式,实现HttpClient的配置。

 

2.3.   回顾以前的配置

springboot入门(转)

 

2.4.   创建工程

springboot入门(转)

 

2.5.   导入依赖

springboot入门(转)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <groupId>cn.itcast.spring</groupId>

   <artifactId>itcast-spring</artifactId>

   <version>0.0.1-SNAPSHOT</version>

 

   <dependencies>

      <!--spring -->

      <dependency>

          <groupId>org.springframework</groupId>

          <artifactId>spring-webmvc</artifactId>

          <version>4.3.7.RELEASE</version>

      </dependency>

      <!--httpclient -->

      <dependency>

          <groupId>org.apache.httpcomponents</groupId>

          <artifactId>httpclient</artifactId>

          <version>4.3.5</version>

      </dependency>

      <!-- 日志 -->

      <dependency>

          <groupId>org.slf4j</groupId>

          <artifactId>slf4j-log4j12</artifactId>

          <version>1.7.7</version>

      </dependency>

   </dependencies>

   <build>

      <plugins>

          <!-- 资源文件拷贝插件 -->

          <plugin>

             <groupId>org.apache.maven.plugins</groupId>

             <artifactId>maven-resources-plugin</artifactId>

             <configuration>

                <encoding>UTF-8</encoding>

             </configuration>

          </plugin>

          <!-- java编译插件 -->

          <plugin>

             <groupId>org.apache.maven.plugins</groupId>

             <artifactId>maven-compiler-plugin</artifactId>

             <configuration>

                <source>1.7</source>

                <target>1.7</target>

                <encoding>UTF-8</encoding>

             </configuration>

          </plugin>

      </plugins>

   </build>

</project>

 

2.6.   属性文件

springboot入门(转)

 

2.7.   编写配置类

基本规则:

1) 用带有@Configuration注解的类来代替以前的XML文件

2) 用@PropertyResource来指定外部属性文件位置(不是必须的)

3) 用@value注解来读取配置文件中的值

4) 用带有@Bean的方法来注册Bean。(方法返回要注册的Bean的对象)

springboot入门(转)

@Configuration// 标记当前类是Spring的配置类

@PropertySource(value = "classpath:httpClient.properties") // 指定属性文件路径

publicclass SpringConfig {

 

    @Value("${http.maxTotal}")

    private Integer maxTotal;// 读取属性文件中的参数

 

    @Value("${http.defaultMaxPerRoute}")

    private Integer defaultMaxPerRoute;

 

    @Value("${http.connectTimeout}")

    private Integer connectTimeout;

 

    @Value("${http.connectionRequestTimeout}")

    private Integer connectionRequestTimeout;

 

    @Value("${http.socketTimeout}")

    private Integer socketTimeout;

 

    @Value("${http.staleConnectionCheckEnabled}")

    private Boolean staleConnectionCheckEnabled;

 

    /**

     注册连接池管理器

     注意:

     *     1)要注册什么类型Bean,返回值就是其类型即可。

     *     2)方法名一般是类型名的首字母小写形式。

     * @return

     */

    @Bean

    public HttpClientConnectionManager httpClientConnectionManager() {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

        connectionManager.setMaxTotal(maxTotal);

        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

        return connectionManager;

    }

 

    // 注册RequestConfig

    @Bean

    public RequestConfig requestConfig() {

        return RequestConfig.custom().setConnectTimeout(connectTimeout)

                .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)

               .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled).build();

    }

    // 注册HttpClient

    @Bean

    public HttpClienthttpClient(HttpClientConnectionManager manager,RequestConfig config) {

        return HttpClientBuilder.create().setConnectionManager(manager).setDefaultRequestConfig(config)

                .build();

    }

}

 

2.8.   编写测试类

publicclass Application {

    publicstaticvoid main(String[] args) throws IOException {

        // 加载Spring容器

        AnnotationConfigApplicationContext context = newAnnotationConfigApplicationContext(SpringConfig.class);

        // 获取HttpClient对象

        HttpClient httpClient = context.getBean(HttpClient.class);

        // 创建get请求

        HttpGet get = new HttpGet("http://www.baidu.com");

        // 发起请求,获取响应

        String content = httpClient.execute(get, newBasicResponseHandler());

       

        System.out.println(content);

        // 销毁容器

        context.close();

    }

}

 

结果:

springboot入门(转)


1.SpringBoot入门

1.1.   概述

在传统的JavaEE开发中,有两大问题一直困扰着我们,一个是复杂的配置,一个是混乱的依赖管理。各种配置其实是开发时的损耗, 因为在思考 Spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。除此之外,项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

 

Spring Boot 让这一切成为了过去。

 

Spring Boot 简化了基于Spring的应用开发,只需要“run”就能创建一个独立的、生产级别的Spring应用。Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认设置),这样我们就可以简单的开始。多数Spring Boot应用只需要很少的Spring配置。

 

我们可以使用SpringBoot创建java应用,并使用java –jar 启动它,或者采用传统的war部署方式。

 

Spring Boot 主要目标是:

l  为所有 Spring 的开发者提供一个非常快速的、广泛接受的入门体验

l  开箱即用(启动器starter-其实就是SpringBoot提供的一个jar包),但通过自己设置参数,即可快速摆脱这种方式。

l  提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等

l  绝对没有代码生成,也无需 XML 配置。

 

官方网站:http://projects.spring.io/spring-boot/

 

1.2.   快速入门

需要注意一点:SpringBoot官方声明兼容的maven版本是3.2及以上版本:

springboot入门(转)

 

1.2.1.        创建工程

springboot入门(转)

可以是jar工程,也可以是war工程。Springboot都支持。

Springboot工程的父工程都是spring-boot-starter-parent。

springboot入门(转)

 

1.2.2.        添加web启动器(依赖)

Spring-boot中已经自动为很多第三方依赖进行了整合并准备了默认配置,我们要使用SpringMVC,不需要任何的配置,只需要导入web项目的启动器,SpringBoot会自动帮我们导入所有依赖,并且完成默认配置。

 

    <dependency>

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

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

    </dependency>

 

注意:其它第三方组件也是如此。例如如果我们要玩mybatis,只需要导入mybatis的启动器即可。

 

此时项目下自动添加了大量依赖:

springboot入门(转)

 

1.2.3.        JDK版本

我们发现默认情况下工程的JDK版本是1.6,但是通常使用的是1.7的版本

springboot入门(转)

 

修改JDK为1.7,需要在pom.xml中添加以下配置:

   <properties>

      <java.version>1.7</java.version>

   </properties>

 

使用Maven更新工程后,就发现版本已经变成1.7了

springboot入门(转)

 

1.2.4.        引导类(启动类)

创建一个引导类,作为入口:

springboot入门(转)

 

SpringBoot内嵌了Tomcat容器,因此我们只需要编写main函数,调用指定的run方法,即可作为一个web项目启动。

// 声明这时一个引导类,程序的入口

@SpringBootApplication

publicclassApplication {

 

   publicstaticvoidmain(String[] args) {

      // 启动容器

      SpringApplication.run(Application.class, args);

   }

}

 

1.2.5.        测试

尝试运行,控制台出现日志:

springboot入门(转)

springboot入门(转)

可以发现Tomcat已经启动了,并且监听了8080端口,映射的路径为/,我们此时访问页面:

springboot入门(转)

因为还没有编写任何的controller,因此内容都没有。此时相当于启动了一个空的Tomcat容器。

 

1.2.6.        我们编写Controller

创建controller包,并且创建HelloController类:

springboot入门(转)

Controller的编写与以前没有区别:

@Controller

publicclassHelloController {

  

   @RequestMapping("hello")

   @ResponseBody

   publicString hello(){

     

      return"helloworld!这是第一个springboot程序";

   }

  

}

 

1.2.7.        Bingo!

重新运行引导类,打开浏览器访问:

springboot入门(转)

OK!

 

1.3.   入门案例分析

可以发现,使用SpringBoot之后,一个整合了SpringMVC的WEB工程开发,变的无比简洁,那些繁杂的配置都消失不见了,这是如何做到的?

 

1.3.1.        启动类

再来看一下引导类:

springboot入门(转)

只是一个普通类,加上了@SpringBootApplication注解。我们查看这个注解源码:

springboot入门(转)

 

这是一个组合式注解,其中核心的注解有三个:

   1)@SpringBootConfiguration

   2)@EnableAutoConfiguration

   3)@ComponentScan

 

l  @SpringBootConfiguration

查看其源码可以发现,这又是一个组合注解,内部整合了Spring中的@Configuration注解:

springboot入门(转)

其作用就是声明这个类是SpringBoot的一个配置类,可以进行各种配置。

 

l  @EnableAutoConfiguration

这个注解的作用是 启用SpringBoot的自动配置功能,查看其说明:

springboot入门(转)

@EnableAutoConfiguration告诉SpringBoot尝试猜测用户希望如何配置Spring,并且实现自动配置。这种自动配置是依据你所引入的依赖来判断的。

在本例中,我们引入了spring-boot-starter-web,而这个里面帮我们引入了tomcat和Spring MVC的依赖:

springboot入门(转)

于是SpringBoot就推测我们需要搭建WEB项目,底层自动帮我们配置了所有Spring和Spring MVC的配置。

 

l  @ComponentScan

源码中的说明:

springboot入门(转)

@ComponentScan注解告诉SpringBoot开始自动扫描指定包下的Spring组件(带有类似@Service注解的类),我们可以通过给注解添加basePackages属性来指定要扫描的包,如果没有指定任何包,默认就会从当前类所在包,及这个包的子包中扫描

 

我们刚才定义的HelloController就在Application所在包的子包中,自然可以被扫描到,并注册到Spring的容器中。

 

1.3.2.        自动配置的原理

1.3.2.1.   自动配置的读取流程

SpringBoot的启动入口要调用SpringApplication的run方法,我们进入这个类,查看源码,其中有一个初始化方法:

springboot入门(转)

继续跟:

springboot入门(转)

继续跟,发现要读取资源文件:

springboot入门(转)

 

查看这个资源文件位置:

springboot入门(转)

 

就在autoconfigure这个包中:

springboot入门(转)

springboot入门(转)

我们打开查看,其中有大量的实现自动配置的接口或类:

springboot入门(转)

 

这些接口和类所在的包:

springboot入门(转)

 

1.3.2.2.   查看SpringMVC的自动配置

在刚才的spring.factoryies中,找到与DispatcherServlet相关的自动配置类:

找到web的自动配置包下的对应类:

springboot入门(转)

查看源码:

springboot入门(转)

这个类的内部类中,有默认配置相关的设置:

springboot入门(转)

 

查看ServerProperties类:

springboot入门(转)

这个类中有一些属性的默认配置,当然也会尝试去读取SpringBoot的全局配置文件(如果存在的话)。

由此自动配置就完成了。

 

1.3.2.3.   结论

SpringBoot其实已经对大量的Spring组件或第三方组件进行了集成,并且进行了大量的默认配置。但是是否使用这些默认配置取决于我们是否添加了这些组件的依赖。

因此,如果我们要启动自动配置,只要引入对应的依赖即可,而SpringBoot给这些第三方组件都添加了启动器(starter),例如前面我们使用的:spring-boot-web-starter,会帮我们默认导入Tomcat及SpringMVC依赖,于是SpringMVC就自动配置完成了。

当然,这些自动配置类中的默认配置并非不能修改,我们可以通过提供一个全局配置文件:application.properties来进行自定义配置

 

使用SpringBoot自动配置步骤:

1) 引入要使用组件的依赖(使用SpringBoot的starter即可)

2) 如果有必要,也可以添加application.properties全局配置

 

那么问题来了:

   问题1:SpringBoot提供了哪些starter呢?

   问题2:全局配置文件该如何配置?

 

1.3.3.        SpringBoot提供的starter

(摘自Spring-boot 1.4.4官方文档)

1. Spring Boot application starters
spring-boot-starter-thymeleaf
使用Thymeleaf视图构建MVC Web应用程序
 
spring-boot-starter-ws
使用Spring Web服务。1.4不推荐使用,推荐使用spring-boot-starter-web-services
 
spring-boot-starter-data-couchbase
Starter for using Couchbase document-oriented database and Spring Data Couchbase
 
spring-boot-starter-artemis
使用Apache Artemis启动JMS消息传递
 
spring-boot-starter-web-services
使用Spring Web服务
 
spring-boot-starter-mail
支持使用Java MailSpring Framework发送电子邮件
 
spring-boot-starter-data-redis
使用Redis键值数据存储与Spring Data RedisJedis客户端
 
spring-boot-starter-web
启动器构建web,包括RESTful,使用Spring MVC的应用程序。使用Tomcat作为默认嵌入式容器
 
spring-boot-starter-data-gemfire
Starter for using GemFire distributed data store and Spring Data GemFire
 
spring-boot-starter-activemq
使用Apache ActiveMQ启动JMS消息传递
 
spring-boot-starter-data-elasticsearch
使用Elasticsearch搜索和分析引擎和Spring Data Elasticsearch
 
spring-boot-starter-integration
Starter for using Spring Integration
 
spring-boot-starter-test
Spring Boot应用程序用于测试包括JUnitHamcrestMockito
 
spring-boot-starter-hornetq
使用HornetQ启动JMS消息传递。1.4已弃用,推荐使用spring-boot-starter-artemis
 
spring-boot-starter-jdbc
使用JDBCTomcat JDBC连接池
 
spring-boot-starter-mobile
使用Spring Mobile构建Web应用程序的入门
 
spring-boot-starter-validation
使用Java Bean校验与Hibernate校验器
 
spring-boot-starter-hateoas
使用Spring MVCSpring HATEOAS构建基于超媒体的RESTful Web应用程序的入门
 
spring-boot-starter-jersey
使用JAX-RSJersey构建RESTful Web应用程序的入门。 spring-boot-starter-web的替代品
 
spring-boot-starter-data-neo4j
使用Neo4j图数据库和Spring Data Neo4j
 
spring-boot-starter-websocket
使用Spring FrameworkWebSocket支持构建WebSocket应用程序
 
spring-boot-starter-aop
使用Spring AOPAspectJ进行面向方面编程
 
spring-boot-starter-amqp
使用Spring AMQPRabbit MQ的入门
 
spring-boot-starter-data-cassandra
使用Cassandra分布式数据库和Spring Data Cassandra
 
spring-boot-starter-social-facebook
使用Spring Social Facebook
 
spring-boot-starter-jta-atomikos
使用Atomikos进行JTA事务
 
spring-boot-starter-security
使用Spring Security
 
spring-boot-starter-mustache
使用Mustache视图构建MVC Web应用程序
 
spring-boot-starter-data-jpa
使用Spring Data JPAHibernate
 
spring-boot-starter
核心启动器,包括自动配置支持,日志记录和YAML
 
spring-boot-starter-velocity
使用Velocity视图构建MVC Web应用程序。1.4已弃用
 
spring-boot-starter-groovy-templates
使用Groovy模板视图构建MVC Web应用程序
 
spring-boot-starter-freemarker
使用FreeMarker视图构建MVC Web应用程序
 
spring-boot-starter-batch
使用Spring Batch
 
spring-boot-starter-redis
使用Redis键值数据存储与Spring Data RedisJedis客户端的入门。1.4已弃用,建议使用spring-boot-starter-data-redis
 
spring-boot-starter-social-linkedin
Stater for using Spring Social LinkedIn
 
spring-boot-starter-cache
支持使用Spring Framework的缓存
 
spring-boot-starter-data-solr
使用带有Spring Data SolrApache Solr搜索平台
 
spring-boot-starter-data-mongodb
使用MongoDBSpring Data MongoDB
 
spring-boot-starter-jooq
使用jOOQ访问SQL数据库。 spring-boot-starter-data-jpaspring-boot-starter-jdbc的替代方法
 
spring-boot-starter-jta-narayana
Spring Boot启动Narayana JTA
 
spring-boot-starter-cloud-connectors
启动者使用Spring Cloud连接器,简化了连接到云平台中的服务,如Cloud FoundryHeroku
 
spring-boot-starter-jta-bitronix
使用Bitronix进行JTA事务
 
spring-boot-starter-social-twitter
使用Spring Social Twitter
 
spring-boot-starter-data-rest
使用Spring Data REST通过REST暴露Spring数据存储库
 
2.  Spring Boot production starters
spring-boot-starter-actuator
使用Spring BootActuator,提供生产就绪的功能,以帮助您监视和管理您的应用程序
 
spring-boot-starter-remote-shell
使用CRaSH远程shell通过SSH监视和管理您的应用程序
 
3. Spring Boot technical starters
spring-boot-starter-undertow
使用Undertow作为嵌入式servlet容器。 spring-boot-starter-tomcat的替代方法
 
spring-boot-starter-jetty
使用Jetty作为嵌入式servlet容器的。 spring-boot-starter-tomcat的替代方法
 
spring-boot-starter-logging
使用Logback进行日志记录。默认日志启动器
 
spring-boot-starter-tomcat
使用Tomcat作为嵌入式servlet容器。 spring-boot-starter-web使用的默认servlet容器
 
spring-boot-starter-log4j2
使用Log4j2进行日志记录。 spring-boot-starter-logging的替代方法

 

1.3.4.        全局配置文件

SpringBoot项目使用一个全局的配置文件application.properties或者是application.yml,在resources目录下或者类路径下的/config下,一般我们放到resources下。

这个配置文件中的属性名该怎么写?不能每次都去源码中查看,所以官网中已经给出了所有配置的示例:

参考:《SpringBoot的全局配置.docx》

springboot入门(转)

 

日志级别设置:

#日志级别

logging.level.org.springframework=DEBUG

 

1.4.   自定义MVC配置

如果我们要自定义配置,可以在resource下创建属性文件:application.properties或者application.yml:

springboot入门(转)

 

1.4.1.        修改默认端口和访问路径

SpringBoot的默认配置中,有关DispatcherServlet的属性如下:

springboot入门(转)

 

我们进行修改:

springboot入门(转)

测试:

springboot入门(转)

页面访问:

springboot入门(转)

 

1.4.2.        访问静态资源

SpringBoot中默认的静态资源存放路径:

springboot入门(转)

 

1.4.2.1.   映射路径为:/

 

以前我们使用SpringMVC的时候,如果拦截的路径是:/

那么静态资源也会进入,就会导致静态资源的404,但是SpringBoot中对静态资源进行了处理,如果访问的是静态资源,会去以下目录中寻找:

   classpath:/META-INF/resources/,

classpath:/resources/,

classpath:/static/,

classpath:/public/

 

因此只要我们把静态资源放到这几个目录,都可以正常访问:

springboot入门(转)

修改访问路径:

springboot入门(转)

访问:

springboot入门(转)

注意:放到WEB项目下的webroot目录下也是支持的。但是如果是jar包方式,是不支持的。只支持war模式。

 

1.4.2.2.   映射路径为:*.xxx

例如:我们配置映射路径为*.html。

那么只有以*.html结尾才会进入SpringMVC。此时静态资源就交给Tomcat处理了,因此spring默认配置的路径是无效的:

访问:

springboot入门(转)

 

2)放到webroot下,再次访问:

springboot入门(转)

测试:

springboot入门(转)

也就是说,以*.xxx结尾的映射,静态资源只有放到webapp目录下才会被访问到。

而jar打包方式,是没有webapp的,也就是说,jar方式打包,如果以*.xxx进行映射,是无法访问静态资源的。

 

1.4.3.        默认的视图解析器

在WebMVC的自动配置类:WebMvcAutoConfiguration中,已经定义了默认的视图解析器

springboot入门(转)

 

其路径前缀和后缀是读取的全局配置:

springboot入门(转)

默认为空:

springboot入门(转)

我们可以在配置文件修改:

springboot入门(转)

页面访问:

springboot入门(转)

由于Spring boot使用的内嵌的tomcat,而内嵌的tamcat是不支持jsp页面的,所有需要导入额外的包才能解决。

<dependency>

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

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

          <scope>provided</scope>

      </dependency>

 

重新启动进行测试:

springboot入门(转)

 

1.4.4.        修改其它配置

在使用SpringMVC的时候,我们经常需要配置例如:消息转换器、拦截器、等内容。官方给出了一种方案:

我们可以通过定义一个类,继承WebMVCConfigureAdapter,然后添加@Configuration注解,再进行自定义配置即可。

我们查看WebMVCConfigureAdapter这个类,其中可以配置的东西非常多:

springboot入门(转)

 

尝试自定义配置:

springboot入门(转)

 

1.5.   读取配置文件的方式

方式1:Spring提供的@Value方式

 

 

方式2:@@PropertySource

 

方式3:SpringBoot提供的属性注入方式。@ConfigurationProperties

比如,在我们的全局配置中有这样两个属性:

springboot入门(转)

 

我们要在配置文件中读取到,应该怎么办呢?

步骤如下:

1)定义一个配置类,添加@Configuration注解,声明这是一个配置类

2)在添加@ConfigurationProperties注解,指定配置文件中属性前缀

3)在类中添加 属性名一致的成员变量

4)提供getter和setter方法

springboot入门(转)

Debug运行,发现属性已经注入:

springboot入门(转)