一:安装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. python appium笔记(二):元素定位

    #这里的示例是用android来说明的,xpath应该是通用的,resource-id不太清楚,没配过IOS的环境 #环境配置和一些参数的意思不清楚可以看我上一篇python appium笔记(一) ...

  2. 盒子模型、网页自动居中、float浮动与清除、横向两列布局

    1.CSS包含:标准文档流,浮动,绝对定位 标准文档流的特点:从上到下,从左到右,输出文档内容 盒子模型:块级元素(div ui li dl dt p)与行级元素(span strong img in ...

  3. 便捷的方式在手机上查看Unity3D的Console Log(调试信息 日志)

    Logs Viewer 功能描述 Using this tool you can easily check your editor console logs inside the game itsel ...

  4. Python面试题(二)【转】

    转载出处http://www.cnblogs.com/goodhacker/p/3387027.html 1.python中类方法.类实例方法.静态方法有何区别? 区别: 类方法和静态方法都可以被类和 ...

  5. MySQL用户远程登录问题

    今天来水一篇,差点被这个远程登录搞死了,所以记录下这个问题. 先使用status命令查看一下MySQL版本,这里可以可以看到我用的是是8.0.12版本. mysql> status ------ ...

  6. June 7. 2018 Week 23rd Thursday

    Half is worse than none at all. 一知半解比一无所知更痛苦. From Westworld. If we go looking for the truth, get th ...

  7. java操作elasticsearch实现批量添加数据(bulk)

    java操作elasticsearch实现批量添加主要使用了bulk 代码如下: //bulk批量操作(批量添加) @Test public void test7() throws IOExcepti ...

  8. Spring Data JPA 简单查询--方法定义规则

    一.常用规则速查 1  And 并且2  Or  或3  Is,Equals 等于4  Between  两者之间5  LessThan 小于6  LessThanEqual   小于等于7  Gre ...

  9. java继承-super的用法

    继承的特点: 1.子类继承了父类的成员 2.具有层次结构 继承的优点: 1.代码重用 2.父类字段和方法可用于子类 3.从抽象到具体形成类的继承体系 4.可以轻松自定义子类 this:当前对象的引用 ...

  10. 完美集群监控组合ganglia和nagios

    Ganglia是伯克利开发的一个集群监控软件.可以监视和显示集群中的节点的各种状态信息,比如如:cpu .mem.硬盘利用率, I/O负载.网络流量情况等,同时可以将历史数据以曲线方式通过php页面呈 ...