一:安装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. WPF:完美自定义MeaagseBox 动画 反弹 背景模糊 扁平化

    不知道为什么,WPF的MeaageBox的风格还停留在Win 2000的风格... 很久前就想自己封装一个MessageBox出来,但是都只是简单的封装,不怎么具有通用性.这次终于搞完了. 使用方法和 ...

  2. Android 与Java 进程退出 killProcess与System.exit

    android所有activity都在主进程中,在清单文件Androidmanifest.xml中可以设置启动不同进程,Service需要指定运行在单独进程?主进程中的主线程?还是主进程中的其他线程? ...

  3. Scala类型限定

    package big.data.analyse.scala /** * 类型限定 * Created by zhen on 2018/12/9. */ object Lxxd { def main( ...

  4. Python中类的定义及使用

    类是一些有共同特征和行为事务事物的抽象概念的总和. 从中可以看出,方法只能使用实例直接调用(无需传self参数),而使用类调用必须传入实例对象: 属性可以使用实例调用,也可以使用类直接调用,因此可以看 ...

  5. c/c++ 通用的(泛型)算法 generic algorithm 总览

    通用的(泛型)算法 generic algorithm 总览 特性: 1,标准库的顺序容器定义了很少的操作,比如添加,删除等. 2,问题:其实还有很多操作,比如排序,查找特定的元素,替换或删除一个特定 ...

  6. UICollectionView 基础

    在iOS开发中经常会用到UICollectionView,和UITableView同样即成UIScrollView 但是操作起来比UITableVIew要麻烦一些 ,有些地方需要注意,一下是UICol ...

  7. win10优化开机进程

    一种比杀毒软件都优化还给力的方法,还在为开机几百个程序启动发愁嘛.一般电脑在重装系统之后的开机进程在50左右,而随着安装程序的增多开机进程将越来越多.下面介绍怎么优化win10进程的方法 之后重启电脑 ...

  8. 如何用fiddler + 手机设置无线代理 下载只有 手机才能访问的资源。

    我主要用来获取,一些特定的API,研究学习. 责任声明: 如果你用来违法犯罪,与我无关. 1.使电脑成为代理服务器 架代理服务器的软件有很多,自己百度一下.也可以用现成的代理软件.(其实Fiddler ...

  9. Teradata超长数据会截断

    1.数据库版本 Teradata 15.10 2.测试案例: create multiset table test_stg ( col1 ) CHARACTER SET LATIN not null ...

  10. P3399 丝绸之路 dp

    题目背景 张骞于公元前138年曾历尽艰险出使过西域.加强了汉朝与西域各国的友好往来.从那以后,一队队骆驼商队在这漫长的商贸大道上行进,他们越过崇山峻岭,将中国的先进技术带向中亚.西亚和欧洲,将那里的香 ...