Spring Boot-Spring Boot入门



Spring Boot


1.springboot介绍

2.使用spring问题

3.springboot特点

4.springboot入门程序

5.restful支持

6.加载配置文件及常量信息

7.springboot集成 spring-data-jpa

8.springboot集成 mybatis

9.springboot集成junit

10.springboot集成log4j

SpringBoot介绍

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

Spring Boot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,能够极大的简化基于Spring  MVC的Web应用和REST服务开发。  Spring  4倡导微服务的架构,针对这一理念,近来在微博上也有一些有价值的讨论,如这里和这里。微服务架构倡导将功能拆分到离散的服务中,独立地进行部署,Spring  Boot能够很方便地将应用打包成独立可运行的JAR包,因此在开发模式上很契合这一理念。 要Spring  Boot进行功能开发,需要使用Gradle或者Maven作为构建工具。

https://www.oschina.net/news/70121/microservice

 

使用spring问题

以往我们做Spring应用开发,要知道配置哪些类来让hibernateSpring一起工作,要知道如何配置view resolver来控制哪个模版进行视图层的展示。经常写了一大堆代码之后发现只是在处理Spring框架本身的配置,根本一行业务逻辑都没有写。开发完成之后,我们还要考虑部署的问题,且不说部署到非常笨重的应用服务器,比如WebSphere, Weblogic或者JBoss,即使部署到Tomcat或者Jetty这种轻量级容器上面,我们要知道如何配置容器,如何修改配置文件等等。而且在多应用部署到同一个Tomcat的时候,经常会出现冲突。就算我们花了很大力气解决了这些问题,程序部署成功之后,我们很难去了解这个程序的运行状态。有可能我们要配置很多第三方工具来去知道这个应用程序运行状态如何,有哪些参数,环境变量是什么。尽管Spring帮我们解决了依赖注入的问题,简化了一些MVC的流程,但是Spring框架本身集成了越来越多东西,导致其越来越难配置,维护成本成直线上升。很多时候Java程序员们看到Python, Ruby或者JavaScript程序员敲几个命令安装一些库,然后简单的敲几行代码,引入一些框架比如flask,然后直接一个简单的API就可以跑起来了。这时候Java程序员可能还在研究该使用Maven里面的哪个库,如何在代码里面进行配置呢。

SpringBoot特点

1.化繁为简,简化配置

 

2.备受关注,是下一代框架

 

3.微服务的入门级框架

 

 

 

 

 

SpringBoot入门程序

5.1 SpringBoot下载

springboot的代码由github.com管理,地址:https://github.com/spring-projects/spring-boot

1.springboot使用maven工程构建 继承父工程 这里使用1.4.3版本

<parent>

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

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

<version>1.4.3.RELEASE</version>

</parent>

 

2.springboot推荐基础pom组件

名称

说明

spring-boot-starter

核心 POM,包含自动配置支持、日志库和对 YAML 配置文件的支持。

spring-boot-starter-amqp

通过 spring-rabbit 支持 AMQP

spring-boot-starter-aop

包含 spring-aop 和 AspectJ 来支持面向切面编程(AOP)。

spring-boot-starter-batch

支持 Spring Batch,包含 HSQLDB

spring-boot-starter-data-jpa

包含 spring-data-jpaspring-orm 和 Hibernate 来支持 JPA

spring-boot-starter-data-mongodb

包含 spring-data-mongodb 来支持 MongoDB

spring-boot-starter-data-rest

通过 spring-data-rest-webmvc 支持以 REST 方式暴露 Spring Data 仓库。

spring-boot-starter-jdbc

支持使用 JDBC 访问数据库。

spring-boot-starter-security

包含 spring-security

spring-boot-starter-test

包含常用的测试所需的依赖,如 JUnitHamcrestMockito 和 spring-test 等。

spring-boot-starter-velocity

支持使用 Velocity 作为模板引擎。

spring-boot-starter-web

支持 Web 应用开发,包含 Tomcat 和 spring-mvc

spring-boot-starter-websocket

支持使用 Tomcat 开发 WebSocket 应用。

spring-boot-starter-ws

支持 Spring Web Services

spring-boot-starter-actuator

添加适用于生产环境的功能,如性能指标和监测等功能。

spring-boot-starter-remote-shell

添加远程 SSH 支持。

spring-boot-starter-jetty

使用 Jetty 而不是默认的 Tomcat 作为应用服务器。

spring-boot-starter-log4j

添加 Log4j 的支持。

spring-boot-starter-logging

使用 Spring Boot 默认的日志框架 Logback

spring-boot-starter-tomcat

使用 Spring Boot 默认的 Tomcat 作为应用服务器。

 

5.2 需求

实现以下功能:

展示一个hello world  jsp页面

 

5.3 工程搭建

 

5.3.1 修改eclipseMaven为默认设置

 

 

 

 

 

 

5.3.2 创建maven工程

 

跳过骨架

 

创建一个jar工程

 

继承spring-boot-starter-parent

 

 

5.3.3 添加工程依赖

<properties>

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

</properties>

<dependencies>

<!-- web 组件 -->

<dependency>

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

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

</dependency>

<!-- spirng boot 开发jsp 页面 -->

<dependency>

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

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

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

</dependencies>

5.3.4 创建工程启动类

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.classargs);

}

 

@SpringBootApplication其作用都是指定springboot启动的main

SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描如果Application类所在的包为:com.itheima,则只会扫描com.itheima包及其所有子包,如果service或dao所在包不在com.itheima及其子包下,则不会被扫描!

5.3.5 创建application.yml核心配置文件

springboot项目在启动时,默认会加载 application.yml配置文件

# 配置 url访问路径及端口号

server:

  context-path: /

  port: 8080

# jsp通配符

spring:

  mvc:

    view:

      prefix: /WEB-INF/jsp/

      suffix: .jsp

application.properties文件也可以,只不过没提示····

5.3.6 创建jsp页面

由于使用maven工程我们创建的是jar包,需要手动创建目录

 

5.3.7 创建表现层

@Controller

public class HelloController {

 

@GetMapping(value="/")

public String index(){

return "helloworld";

}

}

@GetMapping(value="/"等价于

@RequestMapping(value="/",method=RequestMethod.GET)

5.3.8 页面展示

 

RESTful支持

6.1 什么是restful

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。

资源定位:互联网所有的事物都是资源,要求url中没有动词,只有名词。没有参数

Url格式:http://blog.csdn.net/beat_the_world/article/details/45621673

资源操作:使用putdeletepostget,使用不同方法对资源进行操作。分别对应添加、删除、修改、查询。一般使用时还是postgetPutDelete几乎不使用。

6.2 需求

RESTful方式实现信息查询,返回json数据

6.3 方式一

@Controller

public class Rest1Controller {

 

@GetMapping(value = "/rest1/{id}")

public @ResponseBody Object rest1(@PathVariable(value = "id") Integer id) {

 

return id;

}

 

}

6.4 方式二

@RestController

public class Rest2Controller {

 

@GetMapping(value = "/rest2/{id}")

public Object rest2(@PathVariable(value = "id") Integer id) {

 

return id;

}

 

}

 

 

@RestController注解作用=@Controller+@ResponseBody

6.5 总结

springboot整合了

 

及不需要在配置json转换器

加载配置文件及常量信息

7.1 springboot默认加载配置文件

spirngboot项目在启动时会默认加载命名为

 推荐使用有提示

或者

 

7.2 如何加载其他配置文件

项目在扩容时,可能会配置一些常量信息,这些信息不建议放在主配置文件中,这时需要创建一个新的配置文件专门来存放常量信息

 

在核心配置文件中添加

# 加载其他配置文件

spring:

  profiles:

    active: resources

 

默认省略前缀名称

7.3 设置常量信息及注入controller

我们可以在配置文件中增加一个女孩尺码的信息

application-resources.yml

cupSize:  B

GirlController

@RestController

public class GirlController {

@Value(value="${cupSize}")

public String cupSize;

 

@GetMapping(value = "/girl")

public Object girl() {

return cupSize;

}

 

}

7.4 常量封装javaBean

当大量的常量信息,我们每个都需要@value 太繁琐能不能提取成一个专门的javaBean来映射配置文件中的常量呢?

我们可以在配置文件中增加一个女孩 其中有   尺码,年龄

application-resources.yml

girl: 

  cupSize:  B

  age:  18

创建class  GirlProperties

@Component

//IOC注入到 springboot容器中

@ConfigurationProperties(prefix = "girl")

//扫描配置文件常量信息,并且前缀位 girl的内容

public class GirlProperties {

private String cupSize;

private Integer age;

 

GirlController

@RestController

public class GirlController {

@Autowired

private GirlProperties girlProperties;

 

@GetMapping(value = "/girl")

public Object girl() {

return girlProperties;

}

 

}

页面显示

 

SpringBoot集成spring data jpa

8.1 什么是JPA?

JPA就是一个基于O/R映射的标准规范(即实体类和数据库中的表的一种对映)

Spring Data JPA是Spring Data 中的一个子项目,除了它还有Spring Data MongoDB等等

教学链接http://www.ityouknow.com/springboot/2016/08/20/springboot(%E4%BA%94)-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html

8.1.1 自定义简单查询

自定义的简单查询就是根据方法名来自动生成SQL,主要的语法是findXXBy,readAXXBy,queryXXBy,countXXBy, getXXBy后面跟属性名称:

User findByUserName(String userName);

也使用一些加一些关键字And Or

User findByUserNameOrEmail(String username, String email);

修改、删除、统计也是类似语法

Long deleteById(Long id);

Long countByUserName(String userName)

8.1.2 具体的关键字,使用方法和生产成SQL如下表所示

Keyword

Sample

JPQL snippet

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnameIs,findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age ⇐ ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

TRUE

findByActiveTrue()

… where x.active = true

FALSE

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

 

 

8.2 需求

查询数据库item列表信息,并支持条件查询多条件查询

8.3 代码部分

8.3.1 maven依赖

<!-- 使用 spring-data-jpa 操作mysql数据库 -->

<dependency>

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

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

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<!--整合Apache工具组件 -->

<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-commons</artifactId>

</dependency>

<!-- 字符串工具类 -->

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.3.2</version>

</dependency>

 

8.3.2 配置数据库信息

# 配置 url访问路径及端口号

server:

  context-path: /

  port: 8080

 

 

spring:

# jdbc连接信息

  datasource:

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

    url: jdbc:mysql://localhost:3306/mybatis

    username: root

    password: root

# jsp通配符

  mvc:

    view:

      prefix: /WEB-INF/jsp/

      suffix: .jsp

# jpa  hibernate 表创建

  jpa:

    hibernate:

      ddl-auto: update

    show-sql: true

# 加载其他配置文件

  profiles:

    active: resources

8.3.3 pojo映射数据库(hibernate)

工程启动时它会自动映射数据库表信息,如果没有此表在配置文件添加 ddl-auto 会根据此pojo字段信息创建 数据库表

注意 必须创建一个空参构造不然会报错

@Entity(name="items")

public class Items {

 

public Items() {

}

 

@Id

@GeneratedValue

private Integer id;

 

private String name;

 

private Float price;

 

private String detail;

 

private String pic;

 

private Date createtime;

get/set.......

8.3.4 dao

泛型<pojo实体bean,主键ID的类型>

public interface ItemsDao extends JpaRepository<Items, Integer> {

// 根据名称精准 或者 详情模糊查询

List<Items> findByNameAndDetailLike(String name, String detail);

 

// 根据名称精准

List<Items> findByName(String name);

// 详情模糊查询

List<Items> findByDetailLike( String detail);

}

8.3.5 service

实现类

@Service

public class ItemsServiceImpl implements ItemsService {

 

@Autowired

private ItemsDao itemsDao;

 

@Override

public List<Items> findAll() {

return itemsDao.findAll();

}

 

@Override

public List<Items> findByNameOrDetailLike(String name, String detail) {

// 无条件查询

if (name == null && detail == null)

return itemsDao.findAll();

// name

if (detail == null)

return itemsDao.findByName(name);

// detail

if (name == null)

return itemsDao.findByDetailLike("%" + detail + "%");

// 双条件

return itemsDao.findByNameAndDetailLike(name"%" + detail + "%");

}

 

}

8.3.6 controller

@Controller

public class ItemsController {

@Autowired

private ItemsService itemsService;

 

@GetMapping(value = "/")

public String itemList(String name, String detail, Model model) {

//查询service

List<Items> itemList = itemsService.findByNameOrDetailLike(namedetail);

//数据回现

model.addAttribute("itemList"itemList);

model.addAttribute("name"name);

model.addAttribute("detail"detail);

return "itemList";

}

 

}

 

8.3.7 jsp页面

美工妹子开发

 

8.3.8 多条件搜索时问题

多条件搜索时,不输入条件,页面也会默认携带参数(空串)

我们需要配置转换器来清除空串

@Component

public class TrimConvert implements Converter<String, String> {

 

@Override

public String convert(String source) {

if (StringUtils.isNotBlank(source))

return source.trim();

return null;

}

 

}

SpringBoot集成Mybatis

9.1 maven依赖

<!-- springboot 与mybatis集成 -->

<dependency>

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

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

<version>1.1.1</version>

</dependency>

 

9.2 配置mybatis信息

#整合mybatis

mybatis:

  mapper-locations: classpath*:com/itheima/dao/*.xml   #加载配置文件

  type-aliases-package: com.itheima.pojo    #别名

9.3 dao

接口

@Mapper

public interface ItemsDao {

List<Items> findAll();

 

}

 

xml

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

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.itheima.dao.ItemsDao">

 

<select id="findAll" resultType="items">

select * from items

</select>

</mapper>

 

9.4 service

@Service

public class ItemsServiceImpl implements ItemsService {

@Autowired

private ItemsDao itemsDao;

@Override

public List<Items> findAll() {

return itemsDao.findAll();

}

 

}

 

9.4.1 controller

@Controller

public class ItemsController {

@Autowired

private ItemsService itemsService;

 

@GetMapping(value = "/items")

public String items(Model model) {

List<Items> itemList = itemsService.findAll();

model.addAttribute("itemList"itemList);

return "itemList";

}

 

}

10 SpringBoot集成Junit

10.0.1 导入Maven依赖

<!-- springboot 整合junit依赖 -->

<dependency>

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

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

<scope>test</scope>

<exclusions>

<exclusion>

<artifactId>json-smart</artifactId>

<groupId>net.minidev</groupId>

</exclusion>

</exclusions>

</dependency>

</dependencies>

10.1 测试类

@RunWith(SpringJUnit4ClassRunner.class)

 

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

 

@SpringApplicationConfiguration(classes = Application.class)

 

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

//@WebAppConfiguration

public class Mybatis {

@Autowired

private ItemsDao itemsDao;

 

@Test

public void test() {

List<Items> findAll = itemsDao.findAll();

System.out.println(findAll);

}

 

}

 

11 SpringBoot集成Log4j

11.1 9.1 导入maven依赖

SpringBoot 默认是使用logback来进行日志记录的,

需要移除SpringBoot中默认的logback依赖,添加Log4j依赖

 

<dependency>

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

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

<!-- 移除SpringBoot中默认的logback依赖 -->

<exclusions>

<exclusion>

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

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

</exclusion>

</exclusions>

</dependency>

 

<!-- log4j支持 -->

<dependency>

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

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

<version>1.2.5.RELEASE</version>

</dependency>

 

11.2 9.2 添加log4j的配置文件

src的根目录下新建log4j.properties文件,springboot会自动加载该文件为log4j的配置文件,简单的配置如下:

log4j.rootLogger=DEBUG,A1

log4j.logger.org.mybatis = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

 

11.3 不推荐这么玩,因为logback性能好

Spring Boot


1.springboot介绍

2.使用spring问题

3.springboot特点

4.springboot入门程序

5.restful支持

6.加载配置文件及常量信息

7.springboot集成 spring-data-jpa

8.springboot集成 mybatis

9.springboot集成junit

10.springboot集成log4j

SpringBoot介绍

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

Spring Boot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,能够极大的简化基于Spring  MVC的Web应用和REST服务开发。  Spring  4倡导微服务的架构,针对这一理念,近来在微博上也有一些有价值的讨论,如这里和这里。微服务架构倡导将功能拆分到离散的服务中,独立地进行部署,Spring  Boot能够很方便地将应用打包成独立可运行的JAR包,因此在开发模式上很契合这一理念。 要Spring  Boot进行功能开发,需要使用Gradle或者Maven作为构建工具。

https://www.oschina.net/news/70121/microservice

 

使用spring问题

以往我们做Spring应用开发,要知道配置哪些类来让hibernateSpring一起工作,要知道如何配置view resolver来控制哪个模版进行视图层的展示。经常写了一大堆代码之后发现只是在处理Spring框架本身的配置,根本一行业务逻辑都没有写。开发完成之后,我们还要考虑部署的问题,且不说部署到非常笨重的应用服务器,比如WebSphere, Weblogic或者JBoss,即使部署到Tomcat或者Jetty这种轻量级容器上面,我们要知道如何配置容器,如何修改配置文件等等。而且在多应用部署到同一个Tomcat的时候,经常会出现冲突。就算我们花了很大力气解决了这些问题,程序部署成功之后,我们很难去了解这个程序的运行状态。有可能我们要配置很多第三方工具来去知道这个应用程序运行状态如何,有哪些参数,环境变量是什么。尽管Spring帮我们解决了依赖注入的问题,简化了一些MVC的流程,但是Spring框架本身集成了越来越多东西,导致其越来越难配置,维护成本成直线上升。很多时候Java程序员们看到Python, Ruby或者JavaScript程序员敲几个命令安装一些库,然后简单的敲几行代码,引入一些框架比如flask,然后直接一个简单的API就可以跑起来了。这时候Java程序员可能还在研究该使用Maven里面的哪个库,如何在代码里面进行配置呢。

SpringBoot特点

1.化繁为简,简化配置

 

2.备受关注,是下一代框架

 

3.微服务的入门级框架

 

 

 

 

 

SpringBoot入门程序

5.1 SpringBoot下载

springboot的代码由github.com管理,地址:https://github.com/spring-projects/spring-boot

1.springboot使用maven工程构建 继承父工程 这里使用1.4.3版本

<parent>

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

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

<version>1.4.3.RELEASE</version>

</parent>

 

2.springboot推荐基础pom组件

名称

说明

spring-boot-starter

核心 POM,包含自动配置支持、日志库和对 YAML 配置文件的支持。

spring-boot-starter-amqp

通过 spring-rabbit 支持 AMQP

spring-boot-starter-aop

包含 spring-aop 和 AspectJ 来支持面向切面编程(AOP)。

spring-boot-starter-batch

支持 Spring Batch,包含 HSQLDB

spring-boot-starter-data-jpa

包含 spring-data-jpaspring-orm 和 Hibernate 来支持 JPA

spring-boot-starter-data-mongodb

包含 spring-data-mongodb 来支持 MongoDB

spring-boot-starter-data-rest

通过 spring-data-rest-webmvc 支持以 REST 方式暴露 Spring Data 仓库。

spring-boot-starter-jdbc

支持使用 JDBC 访问数据库。

spring-boot-starter-security

包含 spring-security

spring-boot-starter-test

包含常用的测试所需的依赖,如 JUnitHamcrestMockito 和 spring-test 等。

spring-boot-starter-velocity

支持使用 Velocity 作为模板引擎。

spring-boot-starter-web

支持 Web 应用开发,包含 Tomcat 和 spring-mvc

spring-boot-starter-websocket

支持使用 Tomcat 开发 WebSocket 应用。

spring-boot-starter-ws

支持 Spring Web Services

spring-boot-starter-actuator

添加适用于生产环境的功能,如性能指标和监测等功能。

spring-boot-starter-remote-shell

添加远程 SSH 支持。

spring-boot-starter-jetty

使用 Jetty 而不是默认的 Tomcat 作为应用服务器。

spring-boot-starter-log4j

添加 Log4j 的支持。

spring-boot-starter-logging

使用 Spring Boot 默认的日志框架 Logback

spring-boot-starter-tomcat

使用 Spring Boot 默认的 Tomcat 作为应用服务器。

 

5.2 需求

实现以下功能:

展示一个hello world  jsp页面

 

5.3 工程搭建

 

5.3.1 修改eclipseMaven为默认设置

 

 

 

 

 

 

5.3.2 创建maven工程

 

跳过骨架

 

创建一个jar工程

 

继承spring-boot-starter-parent

 

 

5.3.3 添加工程依赖

<properties>

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

</properties>

<dependencies>

<!-- web 组件 -->

<dependency>

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

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

</dependency>

<!-- spirng boot 开发jsp 页面 -->

<dependency>

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

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

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

</dependencies>

5.3.4 创建工程启动类

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.classargs);

}

 

@SpringBootApplication其作用都是指定springboot启动的main

SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描如果Application类所在的包为:com.itheima,则只会扫描com.itheima包及其所有子包,如果service或dao所在包不在com.itheima及其子包下,则不会被扫描!

5.3.5 创建application.yml核心配置文件

springboot项目在启动时,默认会加载 application.yml配置文件

# 配置 url访问路径及端口号

server:

  context-path: /

  port: 8080

# jsp通配符

spring:

  mvc:

    view:

      prefix: /WEB-INF/jsp/

      suffix: .jsp

application.properties文件也可以,只不过没提示····

5.3.6 创建jsp页面

由于使用maven工程我们创建的是jar包,需要手动创建目录

 

5.3.7 创建表现层

@Controller

public class HelloController {

 

@GetMapping(value="/")

public String index(){

return "helloworld";

}

}

@GetMapping(value="/") 等价于

@RequestMapping(value="/",method=RequestMethod.GET)

5.3.8 页面展示

 

RESTful支持

6.1 什么是restful

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。

资源定位:互联网所有的事物都是资源,要求url中没有动词,只有名词。没有参数

Url格式:http://blog.csdn.net/beat_the_world/article/details/45621673

资源操作:使用putdeletepostget,使用不同方法对资源进行操作。分别对应添加、删除、修改、查询。一般使用时还是postgetPutDelete几乎不使用。

6.2 需求

RESTful方式实现信息查询,返回json数据

6.3 方式一

@Controller

public class Rest1Controller {

 

@GetMapping(value = "/rest1/{id}")

public @ResponseBody Object rest1(@PathVariable(value = "id") Integer id) {

 

return id;

}

 

}

6.4 方式二

@RestController

public class Rest2Controller {

 

@GetMapping(value = "/rest2/{id}")

public Object rest2(@PathVariable(value = "id") Integer id) {

 

return id;

}

 

}

 

 

@RestController注解作用=@Controller+@ResponseBody

6.5 总结

springboot整合了

 

及不需要在配置json转换器

加载配置文件及常量信息

7.1 springboot默认加载配置文件

spirngboot项目在启动时会默认加载命名为

 推荐使用有提示

或者

 

7.2 如何加载其他配置文件

项目在扩容时,可能会配置一些常量信息,这些信息不建议放在主配置文件中,这时需要创建一个新的配置文件专门来存放常量信息

 

在核心配置文件中添加

# 加载其他配置文件

spring:

  profiles:

    active: resources

 

默认省略前缀名称

7.3 设置常量信息及注入controller

我们可以在配置文件中增加一个女孩尺码的信息

application-resources.yml

cupSize:  B

GirlController

@RestController

public class GirlController {

@Value(value="${cupSize}")

public String cupSize;

 

@GetMapping(value = "/girl")

public Object girl() {

return cupSize;

}

 

}

7.4 常量封装javaBean

当大量的常量信息,我们每个都需要@value 太繁琐能不能提取成一个专门的javaBean来映射配置文件中的常量呢?

我们可以在配置文件中增加一个女孩 其中有   尺码,年龄

application-resources.yml

girl: 

  cupSize:  B

  age:  18

创建class  GirlProperties

@Component

//IOC注入到 springboot容器中

@ConfigurationProperties(prefix = "girl")

//扫描配置文件常量信息,并且前缀位 girl的内容

public class GirlProperties {

private String cupSize;

private Integer age;

 

GirlController

@RestController

public class GirlController {

@Autowired

private GirlProperties girlProperties;

 

@GetMapping(value = "/girl")

public Object girl() {

return girlProperties;

}

 

}

页面显示

 

SpringBoot集成spring data jpa

8.1 什么是JPA?

JPA就是一个基于O/R映射的标准规范(即实体类和数据库中的表的一种对映)

Spring Data JPA是Spring Data 中的一个子项目,除了它还有Spring Data MongoDB等等

教学链接http://www.ityouknow.com/springboot/2016/08/20/springboot(%E4%BA%94)-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html

8.1.1 自定义简单查询

自定义的简单查询就是根据方法名来自动生成SQL,主要的语法是findXXBy,readAXXBy,queryXXBy,countXXBygetXXBy后面跟属性名称:

User findByUserName(String userName);

也使用一些加一些关键字And Or

User findByUserNameOrEmail(String username, String email);

修改、删除、统计也是类似语法

Long deleteById(Long id);

Long countByUserName(String userName)

8.1.2 具体的关键字,使用方法和生产成SQL如下表所示

Keyword

Sample

JPQL snippet

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnameIs,findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age ⇐ ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

TRUE

findByActiveTrue()

… where x.active = true

FALSE

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

 

 

8.2 需求

查询数据库item列表信息,并支持条件查询多条件查询

8.3 代码部分

8.3.1 maven依赖

<!-- 使用 spring-data-jpa 操作mysql数据库 -->

<dependency>

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

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

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<!--整合Apache工具组件 -->

<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-commons</artifactId>

</dependency>

<!-- 字符串工具类 -->

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.3.2</version>

</dependency>

 

8.3.2 配置数据库信息

# 配置 url访问路径及端口号

server:

  context-path: /

  port: 8080

 

 

spring:

# jdbc连接信息

  datasource:

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

    url: jdbc:mysql://localhost:3306/mybatis

    username: root

    password: root

# jsp通配符

  mvc:

    view:

      prefix: /WEB-INF/jsp/

      suffix: .jsp

# jpa  hibernate 表创建

  jpa:

    hibernate:

      ddl-auto: update

    show-sql: true

# 加载其他配置文件

  profiles:

    active: resources

8.3.3 pojo映射数据库(hibernate)

工程启动时它会自动映射数据库表信息,如果没有此表在配置文件添加 ddl-auto 会根据此pojo字段信息创建 数据库表

注意 必须创建一个空参构造不然会报错

@Entity(name="items")

public class Items {

 

public Items() {

}

 

@Id

@GeneratedValue

private Integer id;

 

private String name;

 

private Float price;

 

private String detail;

 

private String pic;

 

private Date createtime;

get/set.......

8.3.4 dao

泛型<pojo实体bean,主键ID的类型>

public interface ItemsDao extends JpaRepository<Items, Integer> {

// 根据名称精准 或者 详情模糊查询

List<Items> findByNameAndDetailLike(String name, String detail);

 

// 根据名称精准

List<Items> findByName(String name);

// 详情模糊查询

List<Items> findByDetailLike( String detail);

}

8.3.5 service

实现类

@Service

public class ItemsServiceImpl implements ItemsService {

 

@Autowired

private ItemsDao itemsDao;

 

@Override

public List<Items> findAll() {

return itemsDao.findAll();

}

 

@Override

public List<Items> findByNameOrDetailLike(String name, String detail) {

// 无条件查询

if (name == null && detail == null)

return itemsDao.findAll();

// name

if (detail == null)

return itemsDao.findByName(name);

// detail

if (name == null)

return itemsDao.findByDetailLike("%" + detail + "%");

// 双条件

return itemsDao.findByNameAndDetailLike(name"%" + detail + "%");

}

 

}

8.3.6 controller

@Controller

public class ItemsController {

@Autowired

private ItemsService itemsService;

 

@GetMapping(value = "/")

public String itemList(String name, String detail, Model model) {

//查询service

List<Items> itemList = itemsService.findByNameOrDetailLike(namedetail);

//数据回现

model.addAttribute("itemList"itemList);

model.addAttribute("name"name);

model.addAttribute("detail"detail);

return "itemList";

}

 

}

 

8.3.7 jsp页面

美工妹子开发

 

8.3.8 多条件搜索时问题

多条件搜索时,不输入条件,页面也会默认携带参数(空串)

我们需要配置转换器来清除空串

@Component

public class TrimConvert implements Converter<String, String> {

 

@Override

public String convert(String source) {

if (StringUtils.isNotBlank(source))

return source.trim();

return null;

}

 

}

SpringBoot集成Mybatis

9.1 maven依赖

<!-- springboot 与mybatis集成 -->

<dependency>

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

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

<version>1.1.1</version>

</dependency>

 

9.2 配置mybatis信息

#整合mybatis

mybatis:

  mapper-locations: classpath*:com/itheima/dao/*.xml   #加载配置文件

  type-aliases-package: com.itheima.pojo    #别名

9.3 dao

接口

@Mapper

public interface ItemsDao {

List<Items> findAll();

 

}

 

xml

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

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.itheima.dao.ItemsDao">

 

<select id="findAll" resultType="items">

select * from items

</select>

</mapper>

 

9.4 service

@Service

public class ItemsServiceImpl implements ItemsService {

@Autowired

private ItemsDao itemsDao;

@Override

public List<Items> findAll() {

return itemsDao.findAll();

}

 

}

 

9.4.1 controller

@Controller

public class ItemsController {

@Autowired

private ItemsService itemsService;

 

@GetMapping(value = "/items")

public String items(Model model) {

List<Items> itemList = itemsService.findAll();

model.addAttribute("itemList"itemList);

return "itemList";

}

 

}

10 SpringBoot集成Junit

10.0.1 导入Maven依赖

<!-- springboot 整合junit依赖 -->

<dependency>

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

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

<scope>test</scope>

<exclusions>

<exclusion>

<artifactId>json-smart</artifactId>

<groupId>net.minidev</groupId>

</exclusion>

</exclusions>

</dependency>

</dependencies>

10.1 测试类

@RunWith(SpringJUnit4ClassRunner.class)

 

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

 

@SpringApplicationConfiguration(classes = Application.class)

 

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

//@WebAppConfiguration

public class Mybatis {

@Autowired

private ItemsDao itemsDao;

 

@Test

public void test() {

List<Items> findAll = itemsDao.findAll();

System.out.println(findAll);

}

 

}

 

11 SpringBoot集成Log4j

11.1 9.1 导入maven依赖

SpringBoot 默认是使用logback来进行日志记录的,

需要移除SpringBoot中默认的logback依赖,添加Log4j依赖

 

<dependency>

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

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

<!-- 移除SpringBoot中默认的logback依赖 -->

<exclusions>

<exclusion>

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

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

</exclusion>

</exclusions>

</dependency>

 

<!-- log4j支持 -->

<dependency>

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

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

<version>1.2.5.RELEASE</version>

</dependency>

 

11.2 9.2 添加log4j的配置文件

src的根目录下新建log4j.properties文件,springboot会自动加载该文件为log4j的配置文件,简单的配置如下:

log4j.rootLogger=DEBUG,A1

log4j.logger.org.mybatis = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

 

11.3 不推荐这么玩,因为logback性能好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值