一:安装STS插件

二:新建Spring boot项目

  1. 文件 –> 新建 –> Spring Starter Project
  2. 填写类似Mvane项目的一些配置,下一步
  3. 选择依赖:我们只勾选web即可

三:项目开发

1.application.properties与application.yml

1.使用application.properties(默认)

server.port=8081
server.context-path=/demo

2.使用application.yml(手动创建 | 推荐)

server:
  port: 8080
  context-path: /demo

2.1 新建application-dev.yml

server:
  port: 8080
  context-path: /demo
#以下为自定义变量
girl:
  cupSize: A
  age: 18
content: "cupSize: ${cupSize}, age: ${age}"

2.2 新建application.yml

#指定使用哪个子配置
spring:
  profiles:
    active:
    - prod
#配置数据库信息
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        format_sql: true
        hibernate.dialect: org.hibernate.dialect.MySQL5Dialect

2.常用pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.zyzpp</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

    <dependencies>
        <!-- web项目 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 模板引擎 :用于Controller返回html页面
            可以在配置文件修改默认的
            spring.thymeleaf.prefix: /templates/
            spring.thymeleaf.suffix: .html
            -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- 数据库方面 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- AOP面向切面 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!-- 使用 (项目名Properties.class) 类加载application.yml中的自定义变量 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 默认 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

3.如何使用yml中自定义变量

1.第一种方法

    @Value("${cupSize}")
    private String cupSize;

2.第二种方法

package cn.zyzpp.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="girl")//对应yml配置
public class SpringBootDemoProperties {

    private String cupSize;

    private int age;

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

使用时

    @Autowired
    private SpringBootDemoProperties sbdp;
    ....
    sbdp.getCupSize()

4.如何使用Controller

package cn.zyzpp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.zyzpp.properties.SpringBootDemoProperties;

@RestController     //返回json 替代@ResponseBody加@Controller
//@Controller   返回页面
public class HelloController {

    //获取url参数
    //@RequestMapping(value="/hello/{id}", method=RequestMethod.GET)
    @GetMapping(value="/hello/{id}")
    public String say(@PathVariable(name="id") Integer id){
        return id+"";
    }

    //获取请求参数
    @RequestMapping(value={"/hello","/hi"}, method=RequestMethod.GET)   //required= false参数不是必有
    public String sayy(@RequestParam(name="id", required= false, defaultValue="0") Integer id){
        return id+"";
    }

}

5.注释映射数据库表

需要在application.yml配置

package cn.zyzpp.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;

import org.hibernate.validator.constraints.Length;

@Entity
@Table(name="girl")
public class Girl {
    @Id
    @GeneratedValue
    private int id;
    @Min(value=18, message="未成年少女禁止入内")
    private Integer age;
    @Length(min=1,max=1, message="长度必须等于1")
    private String cupSize;

    public Girl() {
        super();
    }

    public Girl(int id, Integer age, String cupSize) {
        super();
        this.id = id;
        this.age = age;
        this.cupSize = cupSize;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getCupSize() {
        return cupSize;
    }
    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }
    @Override
    public String toString() {
        return "Girl [id=" + id + ", age=" + age + ", cupSize=" + cupSize + "]";
    }

}

5.如何配置dao层访问数据库

创建一个接口类即可

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import cn.zyzpp.entity.Girl;

public interface GirlRepository extends JpaRepository<Girl, Integer> {
    /**
     * 通过年龄来查询
     * @return
     */
    public List<Girl> findByAge(Integer age);
}

使用方法

    @Autowired
    private GirlRepository girlRepository;
    ....
    girlRepository.save(girl);
    girlRepository.findOne(id);

6.事务管理

    /**
     * 事务管理测试
     */
    @Transactional
    public void insertTwo(){
        Girl girl = new Girl();
        girl.setAge(19);
        girl.setCupSize("F");
        girlRepository.save(girl);  

        girl = new Girl();
        girl.setAge(20);
        girl.setCupSize("BB");
        girlRepository.save(girl);
    }

7.使用AOP面向切面处理请求

package cn.zyzpp.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
* Created by 巅峰小学生
* 2018年2月27日 下午5:26:41
*/
@Aspect
@Component
public class HttpAspect {
    //开启日志
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    //声明切点
    @Pointcut("execution(public * cn.zyzpp.controller.GirlController.girlFindAll(..))")
    public void pointcut(){}

    //前置通知
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("url={}", request.getRequestURI());
        logger.info("method={}", request.getMethod());
        logger.info("ip={}", request.getRemoteAddr());
        //类方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() );
        //参数
        logger.info("args={}", joinPoint.getArgs());
    }

    //后置通知
    @After("pointcut()")
    public void after(){
        logger.info("后置通知");
    }

    //返回通知
    @AfterReturning(pointcut="pointcut()" ,returning="retrunValue")
    public void afterReturning(Object retrunValue){
        logger.info("response={}", retrunValue.toString());
    }

}

8.统一异常处理

1)自定义异常类

package cn.zyzpp.exception;

import cn.zyzpp.enums.ResultEnum;

/**
* Created by 巅峰小学生
* 2018年2月28日 下午4:17:42
* --自定义异常类
*/
public class GirlException extends RuntimeException {
    private Integer code;

    public GirlException(Integer code, String message) {
        super(message);
        this.code=code;
    }

    public GirlException(ResultEnum resultEnum) {
        super(resultEnum.getMsg());
        this.code=resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

}

2)自定义异常信息

package cn.zyzpp.enums;
/**
* Created by 巅峰小学生
* 2018年2月28日 下午4:54:43
*/
public enum ResultEnum {
    UNKNOW_ERROR(-1, "未知错误"),
    SUCCESS(0, "成功"),
    PRIMARY_SCHOOL(100, "你可能还在上小学" ),
    MIDDLE_SCHOOL(101, "你可能还在上初中"),
    NO_SCHOOL(102, "你可能不上学了"),
    ;

    private Integer code;
    private String msg;

    private ResultEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

}

3)在需要的地方抛出异常

    /**
     * @param id
     * @throws Exception
     */
    public void getAge(int id) throws Exception{
        Girl girl = girlRepository.findOne(id);
        Integer age = girl.getAge();
        if(age < 10){
            throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
        }else if(age>10 && age<16){
            throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
        }else{
            throw new GirlException(ResultEnum.NO_SCHOOL);
        }
    }

4)定义异常捕获类(核心类:上面3步可忽略,直接定义该类即可使用)

package cn.zyzpp.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.zyzpp.controller.GirlController;
import cn.zyzpp.entity.Result;
import cn.zyzpp.exception.GirlException;
import cn.zyzpp.util.ResultUtil;

/**
* Created by 巅峰小学生
* 2018年2月28日 下午3:51:40
*/
@ControllerAdvice
public class ExceptionHandle {

    //记录日志
    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);

    /**
     * 捕获异常 封装返回数据
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<?> handle(Exception e){
        if(e instanceof GirlException){
            return ResultUtil.error(((GirlException) e).getCode(), e.getMessage());
        }else{
            logger.info("[系统异常] {}",e);
            return ResultUtil.error(-1, "未知错误");
        }
    }
}

9.部署在Tomcat服务器

1.)使启动类继承SpringBootServletInitializer 覆写configure()方法。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringBootDemoApplication extends SpringBootServletInitializer{

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

     @Override
     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(SpringBootDemoApplication.class);
      }
}

2.)修改pom.xml打包方式为war

<packaging>war</packaging>

3.)确保嵌入servlet容器不干扰外部servlet容器部署war文件

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
</dependency>
  • 若war在部署到容器中时遇到Project facet Cloud Foundry Standalone Application version 1.0 is not supported.错误;
    解决办法: 项目右键Build Path -> Configure Build Path -> Project facet -> 勾掉Cloud Foundry Standalone Application

2小时学会Spring Boot(IDE:eclipse)的更多相关文章

  1. 2 小时学会 Spring Boot

    一. 什么是 Spring Boot Takes an opinionated view of building production-ready Spring applications. Sprin ...

  2. 2小时学会spring boot 以及spring boot进阶之web进阶(已完成)

    1:更换Maven默认中心仓库的方法 <mirror> <id>nexus-aliyun</id> <mirrorOf>central</mirr ...

  3. spring boot 在eclipse里启动正常,但打包后启动不起来

    现象描述: spring boot 在eclipse里启动正常,但打包后启动不起来. 错误日志如下: D:\Project>java -jar MKKY_CMS.jar . ____ _ __ ...

  4. spring boot框架eclipse快速搭建

    1.maven安装配置好,使用eclipse创建maven项目(选择maven-archetype-quickstart) 2.然后进入http://docs.spring.io/spring-boo ...

  5. Spring boot + Gradle + Eclipse打war包发布总结

    首先感谢两位博主的分享 http://lib.csdn.net/article/git/55444?knId=767 https://my.oschina.net/alexnine/blog/5406 ...

  6. Building a RESTful Web Service Using Spring Boot In Eclipse

    一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...

  7. 一分钟学会Spring Boot多环境配置切换

    一. 问题由来 开发环境.测试环境.生产环境--------我们的软件在不同的环境中,系统参数和配置可能会不一样,比如数据源配置.日志文件配置.以及一些软件运行过程中的基本配置,那每次我们将软件部署到 ...

  8. [DEBUG] spring boot在eclipse中用maven打包成jar访问templates报500错误

    更新:打war包的话只要把html文件放在resources/templates下即可,根本不需要放外面. 配置application.yml和templates放外面这种做法,打war包确实不行. ...

  9. Spring Boot 入门 - 目录

    pring Boot 入门 - 进阶篇(3)- 定时任务(@Scheduled) 主要用于定时发送邮件.夜间自动维护等. (1)开启定时任务功能 @Configuration @EnableSched ...

随机推荐

  1. cmd输出控制台传递的参数

    public class Test2{ public static void main(String[] args){ System.out.println(args[0]); System.out. ...

  2. 第九章 通过 SMB 共享虚拟机

      自 Windows Server 2012 起,微软引入了 SMB 3.0 的概念,通过 SMB 3.0,可以实现很多新的功能,包括我们介绍过的"SMB 多通道",以及将虚拟机 ...

  3. AI学习---分类算法[K-近邻 + 朴素贝叶斯 + 决策树 + 随机森林 ]

    分类算法:对目标值进行分类的算法    1.sklearn转换器(特征工程)和预估器(机器学习)    2.KNN算法(根据邻居确定类别 + 欧氏距离 + k的确定),时间复杂度高,适合小数据    ...

  4. BIZHUB184打印机提示维修召唤(m2)修复

    其他不用管,按照操作直接干:菜单键--常用设置--左键---左键---常用设置--左键---右键      咦  神奇的进入了service mode  服务模式 选择CLEAR DATA 项---- ...

  5. LeetCode算法题-Contains Duplicate(Java实现)

    这是悦乐书的第192次更新,第196篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第52题(顺位题号是217).给定一个整数数组,查找数组是否包含任何重复项.如果数组中至 ...

  6. 我的BRF+自学教程(二):跟踪模式(trace mode)

    使用自开发程序来处理业务逻辑时,处理过程通常是个黑箱,业务顾问和业务用户不知道程序的具体运行方式,要依赖文档和频繁的沟通来确认实际情况. BRFplus可以通过配置的方式实现业务逻辑,使得业务人员把业 ...

  7. mysql+centos7+主从复制

    MYSQL(mariadb) MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可.开发这个分支的原因之一是:甲骨文公司收购了MySQL后,有将MySQL闭源的 ...

  8. Teradata 终止回滚方法(rcvmanager工具)

    1.使用root用户登录数据库节点 ssh root 2.启动database window cnsterm 3.启动rcvmanager start rcvmanager 4.确认utiltiy在哪 ...

  9. ant.design React使用Echarts,实力踩坑

    最近项目用到Echarts(以下用ec代替),于是照猫画虎得引入到团队的antd项目中,但是遇到2个棘手问题: 1. ec对dom不渲染,检查后发现,原来是全局存在id重复,所以使用React时,最好 ...

  10. 解决:Vue刷新/载入页面,出现双括号闪现后消失

    https://cn.vuejs.org/v2/api/#v-cloak v-cloak 不需要表达式 用法: 这个指令保持在元素上直到关联实例结束编译.和 CSS 规则如 [v-cloak] { d ...