【Spring Boot】 从入门到熟练,从简介到集成

来源:互联网 发布:国际学校教师工资 知乎 编辑:程序博客网 时间:2024/05/19 10:56

一、     简介

         Spring BootSpring社区较新的一个项目。该项目的目的是帮助开发者更容易的创建基于Spring的应用程序和服务,让更多人的人更快的对Spring进行入门体验,让Java开发也能够实现Ruby on Rails那样的生产效率。为Spring生态系统提供了一种固定的、约定优于配置风格的框架。

 

         Spring Boot具有如下特性:

·        为基于Spring的开发提供更快的入门体验

·        开箱即用,没有代码生成,也无需XML配置。同时也可以修改默认值来满足特定的需求。

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

·        Spring Boot并不是不对Spring功能上的增强,而是提供了一种快速使用Spring的方式。

 

二、     基础配置

         SpringBoot 使用Maven进行配置,首先新建一个maven项目,在pom.xml里添加如下:

 

    <parent>

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

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

        <version>1.3.0.RELEASE</version>

    </parent>

         增加父pom比较简单,而且spring-boot-starter-parent包含了大量配置好的依赖管理,在自己项目添加这些依赖的时候不需要写<version>版本号。

         使用父pom虽然简单,但是有些情况我们已经有父pom,不能直接增加<parent>时,可以通过如下方式:

<dependencyManagement>

     <dependencies>

        <dependency>

            <!-- Importdependency management from Spring Boot -->

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

            <artifactId>spring-boot-dependencies</artifactId>

            <version>1.2.3.RELEASE</version>

            <type>pom</type>

            <scope>import</scope>

        </dependency>

    </dependencies>

</dependencyManagement>

 

         Spring通过添加spring-boot-starter-*这样的依赖就能支持具体的某个功能。我们最终是要实现web功能,所以添加的是这个依赖。

 

    <dependency>

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

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

     </dependency>

 

         可以使用java.version直接配置使用的java版本:

 

    <properties>

         <java.version>1.8</java.version>

    </properties>

 

 

三、     一个简单的运行

 

         创建一个简单的类:

 

         @RestController

    @SpringBootApplication

    publicclassApplication {

 

        @RequestMapping("/")

       String home() {

           return"HelloWorld!";

        }

 

        @RequestMapping("/now")

       String hehe() {

            return"现在时间:" + (new Date()).toLocaleString();

        }

 

        publicstaticvoidmain(String[] args) {

            SpringApplication.run(Example.class, args);

        }

 

    }

 

Spring Boot建议将我们main方法所在的这个主要的配置类配置在根包名下。

类似如下结构:

com

 +- example

    +- myproject

        +- Application.java

        |

        +- domain

        |   +- Customer.java

        |   +- CustomerRepository.java

        |

        +- service

        |   +- CustomerService.java

        |

        +- web

             +- CustomerController.java

 

 

@RestController

因为我们例子是写一个web应用,因此写的这个注解,这个注解相当于同时添加@Controller@ResponseBody注解。

 

@SpringBootApplication

包含了@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解。Spring Boot建议只有一个带有该注解的类。该注解告诉了Spring Boot程序的入口。

 

启动Spring Boot项目

启动Spring Boot项目最简单的方法就是执行下面的方法:

SpringApplication.run(Application.class, args);

·        1

该方法返回一个ApplicationContext对象,使用注解的时候返回的具体类型是AnnotationConfigApplicationContextAnnotationConfigEmbeddedWebApplicationContext,当支持web的时候是第二个。

除了上面这种方法外,还可以用下面的方法:

SpringApplication application = newSpringApplication(Application.class);

application.run(args);

 

SpringApplication包含了一些其他可以配置的方法,如果你想做一些配置,可以用这种方式。

IDE中直接直接执行main方法,然后访问http://localhost:8080就可以访问到这个项目了。

 

四、     Spring Boot的属性配置

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

 

         这些方式优先级如下:

1.       命令行参数

2.       来自java:comp/envJNDI属性

3.       Java系统属性(System.getProperties()

4.       操作系统环境变量

5.       RandomValuePropertySource配置的random.*属性值

6.       jar包外部的application-{profile}.propertiesapplication.yml(spring.profile)配置文件

7.       jar包内部的application-{profile}.propertiesapplication.yml(spring.profile)配置文件

8.       jar包外部的application.propertiesapplication.yml(不带spring.profile)配置文件

9.       jar包内部的application.propertiesapplication.yml(不带spring.profile)配置文件

10.    @Configuration注解类上的@PropertySource

11.    通过SpringApplication.setDefaultProperties指定的默认属性

 

 

命令行参数:

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

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

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

 

配置文件:

配置文件名为application.propertiesapplication.ymlspring boot会从classpath下的/config目录或者classpath的根目录查找application.propertiesapplication.yml

 

.properties配置文件如:

name=Isea533
server.port=8080

.yml格式的配置文件如:

name: Isea533
server:
    port: 8080
 

常用配置:

         server.port                         web服务器访问端口

    server.context-path                 web服务访问名

    spring.datasource.url                   数据库连接URL
    spring.datasource.username             
数据库连接用户名
    spring.datasource.password             
数据库连接密码

    spring.datasource.driver-class-name 数据库连接驱动

具体其他配置可以点击这里查看

 

五、     Spring Boot 与持久层

SpringBoot 与Mybatis

         首先需要配置好数据源:

                   spring:

             datasource:

                  name:test

                  url:jdbc:mysql://192.168.16.137:3306/test

                username: root

                password:

                #使用druid数据源

                type: com.alibaba.druid.pool.DruidDataSource

                driver-class-name: com.mysql.jdbc.Driver

                filters: stat

                maxActive: 20

                initialSize: 1

                maxWait: 60000

                minIdle: 1

                timeBetweenEvictionRunsMillis:60000

                minEvictableIdleTimeMillis:300000

                validationQuery: select'x'

                testWhileIdle: true

                testOnBorrow: false

                testOnReturn: false

                poolPreparedStatements: true

                 maxOpenPreparedStatements: 20

 

         然后在pom.xml配置Mybatis依赖:mybatis-spring-boot-starter

        <dependency>

             <groupId>org.mybatis.spring.boot</groupId>

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

             <version>1.0.0</version>

        </dependency>

 

         application.yml中增加配置:

                   mybatis:

                          mapperLocations:classpath:mapper/*.xml

                          typeAliasesPackage:tk.mapper.model

除了上面常见的两项配置,还有:

·        mybatis.configmybatis-config.xml配置文件的路径

·        mybatis.typeHandlersPackage:扫描typeHandlers的包

·        mybatis.checkConfigLocation:检查配置文件是否存在

·        mybatis.executorType:设置执行模式(SIMPLE, REUSE,BATCH),默认为SIMPLE

 

配置完这些就可以正常使用Mybatis了。

SpringBoot 与Redis

引入 spring-boot-starter-redis

<dependency>

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

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

 </dependency>

添加配置文件

# REDIS (RedisProperties)

# Redis数据库索引(默认为0

spring.redis.database=0

# Redis服务器地址

spring.redis.host=192.168.0.58

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=

# 连接池最大连接数(使用负值表示没有限制)

spring.redis.pool.max-active=8

# 连接池最大阻塞等待时间(使用负值表示没有限制)

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

# 连接池中的最大空闲连接

spring.redis.pool.max-idle=8

# 连接池中的最小空闲连接

spring.redis.pool.min-idle=0

# 连接超时时间(毫秒)

spring.redis.timeout=0

 

配置完这些,就可以用基本的redis操作了

@Autowired

private StringRedisTemplatestringRedisTemplate;

@Autowired

private RedisTemplate redisTemplate;

@Test

public void test() throws Exception {

    stringRedisTemplate.opsForValue().set("aaa","111");

    Assert.assertEquals("111",stringRedisTemplate.opsForValue().get("aaa"));

}

 

原创粉丝点击