一:安装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. Android绘制优化(一)绘制性能分析

    前言 一个优秀的应用不仅仅是要有吸引人的功能和交互,同时在性能上也有很高的要求.运行Android系统的手机,虽然配置在不断的提升,但仍旧无法和PC相比,无法做到PC那样拥有超大的内存以及高性能的CP ...

  2. 个人项目:Java实现WC

    Java实现WC Github项目地址:https://github.com/auxshaw/WC 项目要求 wc.exe 是一个常见的工具,它能统计文本文件的字符数.单词数和行数.这个项目要求写一个 ...

  3. shell编程-输出(六)

    echo输出echo指令用于字符串的输出 格式:echo 字符串 直接输出字符串:string echo 'this is string-output' 用双引号,这儿也可以省略引号 转义字符:\ e ...

  4. mssql sqlerver 脚本 计算数据表的结余数的方法分享

    转自:http://www.maomao365.com/?p=5710 摘要:今天接到一个需求,有一张数据表,记录的是消费明细数据,现在需要做一个累计结余,记录每次的数据结余合计,下文将展示一种sql ...

  5. 【PAT】B1007 素数对猜想

    素数筛筛出规定范围内的所有素数存入数组 遍历数组,如果满足于后边的差2,计数器加加 #include <cstdio> const int maxn = 10000001; int pri ...

  6. June 1. 2018 Week 22nd Friday

    What makes life dreary is the want of motive. 没有了目的,生活便暗淡无光. We all have dreams about our future, we ...

  7. 别老扯什么hadoop,你的数据根本不够大

    本文原名“Don't use Hadoop when your data isn't that big ”,出自有着多年从业经验的数据科学家Chris Stucchio,纽约大学柯朗研究所博士后,搞过 ...

  8. JWT 认证 以及Django 中的应用

    jwt 认证 私钥.公钥.CA认证 用一套加密规则 加密和解密 RSA加密 (非对称的加密) 摘要算法:MD5 FTP/互联网下载软件校验MD5 私钥 --RSA算法-->公钥 RSA原理 加密 ...

  9. 设计模式のCommand Pattern(命令模式)----行为模式

    一.产生背景 熟悉计算机的同学应该清楚,用户发出各种命令,CPU执行命令,OS负责调度.命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式.请求以命令的形式包裹在对象 ...

  10. centos下安装 glances 的问题

    开始想安装htop 然后 yum installhtop 没有 yum searchhtop 也没有  然后上github 发现一个比htop还华丽的东西. Glances 大概这个样子的. 可以一览 ...