Spring Boot框架集成

0、为什么使用Spring Boot?

   Spring框架由于其繁琐的配置,一度被人认为“配置地狱”,各种XML、Annotation配置混合使用,让人眼花缭乱,而且如果出错了也很难找出原因。通过SpringMVC框架部署和发布web程序,需要和系统外服务器进行关联,操作繁琐不方便。

   Spring Boot是由Spring官方推出的一个新框架,对Spring进行了高度封装,是Spring未来的发展方向。使用Spring Boot框架后,可以帮助开发者快速搭建Spring框架,也可以帮助开发者快速启动一个Web服务,无须依赖外部Servlet容器,使编码变得单,使配置变得简单,使部署变得简单,使监控变得简单。

1、创建Maven Web项目

在 IDE 中创建Maven Web项目,无需配置web.xml文件。spring Boot框架开发web系统,是基于servlet3.0或以上规范,无需web.xml文件

修改项目中的pom.xml文件,设置JDK编译版本为1.8。Spring Boot框架最低JDK版本要求1.6

<project>
    ...
    <build>
        <plugins>
            <!-- 修改maven默认的JRE编译版本,1.8代表JRE编译的版本,根据自己的安装版本选择填写,最低1.6 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>

2、集成Spring Boot框架

修改pom.xml文件,增加Spring Boot框架的依赖关系及对Web环境的支持。

<project>
    ...
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>
    ...
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    ...
</project>

在SSM项目中,所有类库的依赖关系都需要我们自己导入到pom.xml文件中,但是Spring Boot项目增加spring-boot-starter-web依赖后,会自动加载web环境配置相关依赖(SpringMVC, Tomcat),简化了我们的操作。

spring-boot-starter-parent:继承Spring Boot的相关参数;

spring-boot-starter-xxx:代表一个Spring Boot模块;

*集成环境后,增加程序代码进行演示

package com.springboot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {

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

Spring Boot项目中都会有一个以Application结尾的应用类,然后有一个标准的Java入口方法main方法。通过这个方法启动Spring Boot项目,方法中无需放入任何业务逻辑。

@SpringBootApplication注解是Spring Boot核心注解。

右键点击项目或项目中的 SpringbootApplication 类, 选择菜单Run as → Spring Boot App,即可启动项目服务。

Spring Boot框架中集成了Tomcat服务器。当增加Web依赖后执行main方法,等同于启动Tomcat服务器, 默认端口号为8080。你会发现,这样的开发方式比传统的Spring Web项目开发简单了很多。若要修改默认的Tomcat服务器端口号,可以通过全局配置文件进行配置,在src/main/resources/目录中增加application.properties文件。

server.context-path=/
server.port=80
server.session.timeout=60
server.tomcat.max-threads=800
server.tomcat.uri-encoding=UTF-8

Spring Boot会自动读取src/main/resources/路径或类路径下/config路径中的application.properties文件或application.yml文件。

3、集成Spring & SpringMVC框架

基本的Spring Boot环境已经上面已经构建好了,现在需要配置Spring框架及SpringMVC框架的业务环境。

在 SpringbootApplication 类中启用扫描功能,增加@ComponentScan注解;

package com.springboot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;


@ComponentScan(basePackages="com.springboot")
@SpringBootApplication
public class SpringbootApplication {

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

}

在当前代码中,@ComponentScan注解即使不使用,框架也可以自动进行扫描,但是扫描的包是当前包com.springboot.demo和子包com.springboot.demo.*;如果还需要扫描其他的包,那么需要增加@ComponentScan注解。

在src/main/java目录中增加类 com.springboot.demo.controller.UserController,并增加相应代码。

package com.springboot.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {

	@ResponseBody
	@RequestMapping("/index")
	public Object index() {
		Map map = new HashMap();
		map.put("username", "张三");
		return map;
	}
}

执行SpringbootApplication类中main方法。然后访问路径http://127.0.0.1:8080/应用路径名称/user/index;页面打印JSON字符串即可。

Service接口,ServiceImpl实现类的使用和SSM架构中的使用方式完全相同。

* 问:@Controller 和 @RestController的区别

答:官方文档:@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
表示@RestController等同于@Controller + @ResponseBody。

4、集成Mybatis框架

Spring Boot框架在集成Mybatis框架的时候依然要扫描Dao接口,SQL映射文件以及依赖数据库连接池,但是和传统SSM框架集成时稍微有一些不同。

在项目pom.xml文件中增加Mybaits相关依赖类库(连接池,数据库驱动程序等)。

<project>
    ...
    <dependencies>
        ...
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        ...
    </dependencies>
    ...
</project>

src/main/resources/目录下,增加application.yml配置文件,增加连接池和mybatis相关配置;

spring: 
  datasource:  
    name: mydb  
    type: com.alibaba.druid.pool.DruidDataSource  
    url: jdbc:mysql://127.0.0.1:3396/springboot 
    username: root  
    password: root  
    driver-class-name: com.mysql.jdbc.Driver   
mybatis:   
  mapperLocations: classpath*:mybatis/mapper-*.xml  
  typeAliasesPackage: com.springboot.**.bean

*问:.properties配置文件和.yml配置文件有什么区别?

答:在 Spring Boot 中,有两种配置文件,一种是application.properties,另一种是application.yml,两种都可以配置Spring Boot 项目中的一些变量的定义,参数的设置等。application.properties 配置文件在写的时候要写完整,yml文件在写的时候层次感强,而且少写了代码。但是从严格意义上来讲,区别不大。

*扫描Dao接口,需要在SpringbootApplication类中增加扫描注解@MapperScan("com.springboot.**.dao")及事务管理@EnableTransactionManagement;

package com.springboot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.springboot.**.dao")
@EnableTransactionManagement
@SpringBootApplication
public class SpringbootApplication {

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

在src/main/java目录中增加com.springboot.demo.dao.MemberDao接口,相应代码略;
在src/main/java目录中增加com.springboot.demo.bean.Member实体类,相应代码略;
传统的SSM架构中采用的是声明式事务,需要在配置文件中增加AOP事务配置,Spring Boot框架中简化了这种配置,可以在Service接口中增加注解@Transactional,相应代码略;

重启服务,访问路径http://127.0.0.1:8080/应用路径名称/user/index 即可观察效果。

*问:Spring Boot项目在不同的环境下(开发,测试,生产),服务端口不一致怎么办?

答:Spring Boot针对于不同的环境提供了Profile支持。通过profile的设定来查找不同的配置文件,如果application.properties配置文件中增加配置参数spring.profiles.active=test,那么框架会自动读取application-test.properties文件,在不同的配置文件中设定不同的端口号(8182。。。)即可。也可以将项目打包成jar,输入命令行参数:java -jar xxx.jar --spring.profiles.active=test。

5、模板视图 - freemarker

项目中采用freemarker作为展示视图,需要在项目pom.xml配置文件中增加依赖关系。

<project>
    ...
    <dependencies>
        ...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        ...
    </dependencies>
    ...
</project>

application.properties配置文件中增加freemarker相关配置。

...
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=true
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true  
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.prefer-file-system-access=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true 
spring.freemarker.order=1
...

src/main/resources/目录中增加templates文件夹,并增加以.ftl结尾的文件,如userIndex.ftl。

*问:Spring Boot中为什么不采用JSP作为视图模板?

答:Spring Boot框架一般是打包为JAR执行,而JSPweb工程(war包)中可以被java程序读取和识别,但是在JAR包中是比较困难的。所以需要采用其他的模板视图技术。

6、热部署

项目开发过程中,常常会改动页面数据或者修改数据结构,为了显示改动效果,往往需要重启应用查看改变效果,其实就是重新编译生成了新的 Class 文件,这个文件里记录着和代码等对应的各种信息,然后 Class 文件将被虚拟机的 ClassLoader 加载。而热部署正是利用了这个特点,它监听到如果有 Class 文件改动了,就会创建一个新的 ClaassLoader 进行加载该文件,经过一系列的过程,最终将结果呈现在我们眼前。

Spring Boot 实现热部署很简单,在pom.xml中增加相关依赖即可;

<dependencies>
    ...
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional><!-- 这个需要为 true 热部署才有效-->
    </dependency>
    ...
</dependencies>

*问:如何将Spring Boot项目发布为war包独立部署?

答:1)将当前的项目打包方式设置为war

       2)将项目中tomcat模块的依赖类库设置为provided

...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
...

     3)将当前Application启动类继承SpringBootServletInitializer, 并重写方法configure

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
	builder.sources(Application.class);// Application为启动类
	return super.configure(builder);
} 

7、健康监控

在生产环境中,需要实时或定期监控服务的可用性。Spring Boot 的actuator(监控)功能提供了很多监控所需的接口。

pom.xml文件中增加依赖关系;

...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
...

application.yml配置文件中指明监控端口,如果未指明,那么监控端口和当前应用端口一致。

...
management:  
  port: 8400
...

application.yml配置文件中增加环境信息,数据可从pom.xml文件中获取。

...
info:  
  app:  
    name: "@project.name@" #从pom.xml中获取  
    description: "@project.description@"  
    version: "@project.version@"  
    spring-boot-version: "@project.parent.version@"
...

输入网址http://localhost:8400/info查看配置;具体监控指标如下:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值