springboot

来源:互联网 发布:激光割算法公式 编辑:程序博客网 时间:2024/05/20 23:32

springboot简介

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解,就是spring boot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架(不知道这样比喻是否合适)。
springboot容器
spring容器提供了bean的创建和管理 spring沿用spring容器 提供了简化的操作方式 全程使用注解 以下通过实例讲解bean的管理 构建项目使用maven
使用maven建立普通的maven jar项目
pom.xml内容(可以通过sts生成)

<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.et</groupId>    <artifactId>SbLesson</artifactId>    <version>0.0.1-SNAPSHOT</version>    <!-- 继承自springboot的依赖 -->    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.9.RELEASE</version>    </parent>    <dependencies>    <!--        springboot每一个框架的集成都是一个starter         spring-boot-starter-web加载javaee 内嵌tomcat    所有库参考 https://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/reference/htmlsingle/#using-boot-starter       -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>        <!-- 可直接访问jsp的配置 使用jsp添加的依赖 -->            <groupId>org.apache.tomcat.embed</groupId>            <artifactId>tomcat-embed-jasper</artifactId>        </dependency>         <!-- 使用连接数据的starter -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>        <!-- 应用freemarker的starter -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-freemarker</artifactId>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.35</version>        </dependency>        <!-- druid的配置             https://github.com/mybatis        -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>            <version>1.1.5</version>        </dependency>        <!-- 继承mybatis的配置 -->         <dependency>             <groupId>org.mybatis.spring.boot</groupId>             <artifactId>mybatis-spring-boot-starter</artifactId>             <version>1.3.1</version>          </dependency>          <!-- 用于监控 项目是否安全 -->           <dependency>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-starter-actuator</artifactId>            </dependency>            <!--开发工具  添加启动配置 -->           <dependency>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-devtools</artifactId>                <optional>true</optional>            </dependency>    </dependencies>      <!--springboot项目发布 使用spring-boot-maven-plugin插件-->      <build>          <plugins>              <plugin>                  <groupId>org.springframework.boot</groupId>                  <artifactId>spring-boot-maven-plugin</artifactId>              </plugin>          </plugins>      </build>  </project>

创建包 com.et.lesson01创建类SbApplication 用于启动springboot
SpringBootApplication是EnableAutoConfiguration 子类 启用spring的自动配置功能

@ComponentScan("com.et.lesson01") 自动扫描和装配 (@Controller Component等) @ComponentScan指定扫描特定的包 默认是扫描当前main的子包  @EnableAutoConfiguration   启用自动配置public class SbApplication {      public static void main(String[] args) {          SpringApplication.run(SbApplication.class, args);      }  }  

添加springmvc的控制类 com.et.controller.SbController 默认springboot只会扫描启动类相同包或者子包中带有注解的bean

** * @EnableAutoConfiguration 自动配置注解 * @RestController 控制层注解 * @author Administrator * 必须添加SpringBootApplication 启用spring的自动配置功能 */@RestController@SpringBootApplicationpublic class SbController {    /**     * 只需要配置application.properties的四要素 即可使用该类     *  spring.datasource.url=jdbc:mysql://localhost/userinfo        spring.datasource.username=root        spring.datasource.password=123456        spring.datasource.driver-class-name=com.mysql.jdbc.Driver     */    @Autowired    EmpService service;    /**     * 使用springmvc的例子     */    @RequestMapping("/hello")    public Map hello(){        return service.hello();    }    /**     * 使用jdbctemplate的例子     */    @RequestMapping("/emp/{empId}")    public Map getEmp(@PathVariable String empId){        return service.getEmp(empId);    }    /**     * 使用hibernate添加的例子     */    @RequestMapping("/saveEmp")    public String saveEmp(){        return service.saveEmp();    }    /**     * 使用hibernate查询例子     */    @RequestMapping("/queryEmp")    public Emp querEmp(){        return service.querEmp();    }    /**     * 使用hibernate删除例子     */    @RequestMapping("/deleteEmp/{id}")    public void deleteEmp(@PathVariable Integer id){         service.deleteEmp(id);    }    /**     * 使用hibernate修改例子     */    @RequestMapping(value="/updateEmp/{id}")    public void updateEmp(@PathVariable Integer id){        service.updateEmp(id);    }    public static void main(String[] args) {        SpringApplication.run(SbController.class, args);    }}

运行主类SbApplication 通过日志查看发现默认启动了tomcat端口 8080
springboot默认读取src/main/resources下的application.properties或者application.yml文件 该文件时springboot的配置文件
比如配置端口 server.port=80 可以修改tomcat端口 其他配置参考springboot官方文档
(https://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/reference/htmlsingle/#common-application-properties)

apllication.properties中spring.datasource.url=jdbc:mysql://localhost/数据库名spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver//连接池spring.datasource.type=com.alibaba.druid.pool.DruidDataSource//自动启动运行的主类spring.devtools.restart.enabled=true//显示sql语句spring.jpa.show-sql=true//修改端口server.port=8080//上下文路径server.context-path=/sbdebug=true

hibernate映射生成sql语句

import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;/** *  * @author Administrator *@GeneratedValue 主键生成的策略 */@Entitypublic class Emp {    @Id    @GeneratedValue(strategy=GenerationType.AUTO)    private int id;    @Column    private String ename;    @Column    private double sal;    @Column    private int deptid;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getEname() {        return ename;    }    public void setEname(String ename) {        this.ename = ename;    }    public double getSal() {        return sal;    }    public void setSal(double sal) {        this.sal = sal;    }    public int getDeptid() {        return deptid;    }    public void setDeptid(int deptid) {        this.deptid = deptid;    }   }
/** * 自定义一个接口继承自CrudRepository即可  * interface EmpRepository extends CrudRepository<操作实体类型, 主键类型> */public interface EmpRepository extends CrudRepository<Emp, Integer> {}

springboot的常用配置

开发工具
springboot包含了一些开发工具集 只需要引用 spring-boot-devtools 依赖 开发工具在开发阶段默认开启 在被打包的程序 比如jar包 通过 java -jar运行
自动禁用 开发工具集

<dependencies>      <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-devtools</artifactId>          <optional>true</optional>      </dependency>  </dependencies>  

在spring.properties添加启动配置 (添加了maven依赖 该参数默认为true 如果想禁用 改成false)

spring.devtools.restart.enabled=true

自定义Banner
springboot默认启动时 输出的图标就是banner 比如

 .   ____          _            __ _ _   /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \  ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \   \\/  ___)| |_)| | | | | || (_| |  ) ) ) )    '  |____| .__|_| |_|_| |_\__, | / / / /   =========|_|==============|___/=/_/_/_/   :: Spring Boot ::        (v1.5.7.RELEASE)  

spring提供了自定义banner的方式在 src/main/resources添加文件banner.txt 添加特殊的自定义符号 在该txt中可以使用资源文件的一些特殊信息

比如我的banner.txt为

// o8888888o //// 88" . "88 //// (| ^_^ |) //// O\ = /O //

springboot集成mybatis

一.pom.xml引入依赖

<dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.25</version>    </dependency>    <dependency>        <groupId>com.alibaba</groupId>        <artifactId>druid</artifactId>    </dependency>    <!-- mybatis -->    <dependency>        <groupId>org.mybatis.spring.boot</groupId>        <artifactId>mybatis-spring-boot-starter</artifactId>        <version>1.2.0</version>    </dependency>

二.application.properties中数据源配置,使用druid连接池

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

如果要使用Druid的内置监控功能,需要配置数据源时加上

<property name="filters" value="stat" />

还需要在web.xml中加上:

<!-- 启用Web监控统计功能需要在Web应用的web.xml中加入这个Servlet声明 -->    <servlet>        <servlet-name>DruidStatView</servlet-name>        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>        <init-param>            <!-- 是否允许清空统计数据,不写时默认true -->          <param-name>resetEnable</param-name>            <param-value>true</param-value>            </init-param>            <init-param>            <!-- 用户名,用户名和密码可以不写,不写时不需要输入,直接登录 -->          <param-name>loginUsername</param-name>            <param-value>druid</param-value>            </init-param>            <init-param>            <!-- 密码 -->          <param-name>loginPassword</param-name>            <param-value>123456</param-value>          </init-param>      </servlet>    <servlet-mapping>        <servlet-name>DruidStatView</servlet-name>        <url-pattern>/druid/*</url-pattern>    </servlet-mapping>  

springboot中不支持web.xml如何用springboot集成mybatis创建web.xml如下:

/** * @author Administrator *@Configuration通过类的注解产生bean */@Configurationpublic class ConfigBean {    /**     * 相当于<bean id="druidSRegistrationBean" calss="ServletRegistrationBean">     * @return     */    @Bean    public ServletRegistrationBean druidStatView(){        /**         * <servlet-name>DruidStatView</servlet-name>           * <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>           */        ServletRegistrationBean srb=new ServletRegistrationBean();        //servlet的名字        srb.setName("DruidStatView");        StatViewServlet ss=new StatViewServlet();        srb.setServlet(ss);        //设置拦截的路径        String url="/druid/*";        List<String> urls=new ArrayList<String>();        urls.add(url);        srb.setUrlMappings(urls);        //设置用户名和密码        LinkedHashMap<String, String> link=new LinkedHashMap<String, String>();        link.put("loginUsername", "admin");        link.put("loginPassword","123456");        srb.setInitParameters(link);        return srb;    }}

例子:

/** * @EnableAutoConfiguration 自动配置注解 * @RestController 控制层注解 * @author Administrator * 必须添加SpringBootApplication 启用spring的自动配置功能 */@RestControllerpublic class SbController {    @Autowired    DataSource dataSource;    @Autowired    EmpMapper mapper;    @RequestMapping("/syso")    public String hello(){        return dataSource.toString();    }    /**     * 查询所有     * @return     */    @RequestMapping("/queryAll")    public List<Emp> queryAll(){        return mapper.queryEmp();    }    /**     * 查询所有     * @return     */    @RequestMapping("/queryId/{id}")    public Emp queryEmpById(@PathVariable Integer id){        return mapper.queryById(id);    }}
public class Emp {    private int id;    private String ename;    private double sal;    private int deptid;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getEname() {        return ename;    }    public void setEname(String ename) {        this.ename = ename;    }    public double getSal() {        return sal;    }    public void setSal(double sal) {        this.sal = sal;    }    public int getDeptid() {        return deptid;    }    public void setDeptid(int deptid) {        this.deptid = deptid;    }}
import java.util.List;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Select;import com.et.lesson02.entity.Emp;@Mapperpublic interface EmpMapper {    /**     * 查询所有     * @return     */    @Select("select * from emp")    List<Emp> queryEmp();    /**     * 通过id查询     * @return     */    @Select("select * from emp where id=#{0}")    Emp queryById(int id);}
/** * @SpringBootApplication 启动spring的自动配置功能 * @ComponentScan("com.et.lesson02.mapper") 扫描 * @author Administrator * springboot如何注册servlet */@SpringBootApplicationpublic class Main {    public static void main(String[] args) {        //启动会加载自动配置         SpringApplication.run(Main.class, args);    }}