Spring-Boot框架

1. spring boot 简介

Spring Boot 是由 Pivotal 团队提供的全新框架。Spring Boot 是所有基于 Spring Framework 5.0 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的配置文件。

1.1 springboot的好处

① 创建独立的 Spring 应用程序
② 嵌入的 Tomcat,无需部署 WAR 文件
③ 简化 Maven 配置
④ 自动配置 Spring
⑤ 开箱即用,没有代码生成,也无需 XML 配置。

1.2 spring boot 快速入门

(1)JDK 环境必须是 1.8 及以上,传送门:jdk1.8.191 下载
(2)后面要使用到 Maven 管理工具 3.2.5 及以上版本.
(3)开发工具建议使用 IDEA

创建步骤

 

 

 默认springboot扫描的包为主启动类所在的包以及子包。

测试:

@RestController
public class Hello {
   @GetMapping("/hello")
    public Map<String ,Object> hello(){
        Map<String,Object> map=new HashMap<>();
        map.put("name","wang");
        return map;
    }
}

 运行程序

 1.3 springboot的配置文件

 第一种: properties属性文件

  # 修改springboot中tomcat端口号.
    server.port=8888

第二种:  yml文件
    server:
    port: 6666

不管是哪种,他们的名字必须以application开始。
如果两个配置文件同时存在,而且有些内容一样。按照properties的优先级高。
如果有些不一样,两个配置文件不一样的会合并在一起。

yml文件的语法

student:
  id: 1
  name: xiaoming
  age: ${a.age}
  hobby:
    - LOL
    - DNF
    - CF
    - LOL
  lists:
    - LOL
    - DNF
  maps:
    k1: v1
    k2: v2
  sets:
    - LOL
    - DNF
    - CF
    - LOL
  birth: 2019/12/12
a:
  age: ${random.int(1,100)}

Properties 没有层级关系 使用=赋值

yml 有层级关系 使用: 赋值

两种语法的配置是互补的

读取springboot配置文件中的内容

在application.properties中写入

student.name=zs
student.age=18
student.hobby[0]=sing
student.hobby[1]=swimming
student.map.clazz=qy151

创建实体类 将读取application.properties配置文件中的值并赋值给Student类中的属性

@Data
@Component //该类对象的创建和销毁都有spring容器来管理
@ConfigurationProperties(prefix = "student") //读取springboot中的配置内容,读取以前缀为student
public class Student {
    String name;
    String age;
    String[] hobby;
    Map<String,Object> map;
}

 

读取application.yml配置文件中的值并赋值给Student类中的属性

server:
  port: 8082

student:
  name: zs
  age: 18
  hobby:
    - sing
    - dance
    - rap
    - basketball
  map:
    clazz: qy151

 

@Value 只能放在我们的类属性上。而且它只能读取基本类型和字符串类型。

1.4 profiles配置详解

为什么要使用profiles?

在开发中,一般有两种环境
    1,生产环境  [项目上线,客户在使用中,就是生产环境]
    2,开发环境[就是开发环境,不解释]
    有时候开发环境和生产环境的配置方法是不一样的,那么如何快速的切换呢,这里就要使用profiles文件

使用方法

1,创建applicatin-developer.properties
 
server.port=8081
2,创建applicatin-product.properties
 
server.port=8082
3,修改application.properties
 
#server.port=8080
spring.profiles.active=developer
4. 测试
5,总结
在application.properteis里面激活哪个文件就会使用哪个端口

2. WEB三大组件的注册

web的三个组件: Servlet和Filter以及Linstener监听器。

2.1 注册Servlet

创建Servlet

public class MyServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("这时自己定义的servlet~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }
}

配置类

@Configuration //该类为配置类 xml文件
public class MyConfig {

    @Bean  //理解为配置文件中<bean >
    public ServletRegistrationBean<Servlet> registrationBean(){
        //创建一个Servlet注册器.
         ServletRegistrationBean<Servlet> registrationBean=new ServletRegistrationBean<>();
         registrationBean.setName("my");
         registrationBean.setServlet(new MyServlet());
         registrationBean.addUrlMappings("/my");
         return registrationBean;
    }

  }

2.2 注册Filter

创建Filter

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("经过了过滤器");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

配置类

@Configuration //该类为配置类 xml文件
public class MyConfig {
    @Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean(){
          FilterRegistrationBean<Filter> filterRegistrationBean=new FilterRegistrationBean<>();
          filterRegistrationBean.setName("myfilter");
          filterRegistrationBean.setFilter(new MyFilter());
          filterRegistrationBean.addUrlPatterns("/*");
          return filterRegistrationBean;
    }
}

3. springboot自动装配

自动装配在SpringBoot是基于EnableAutoConfiguration来实现的。springboot的自动装配启动类上的注解@SpringBootApplication有关

spring boot自动装配原理

注解@EnableAutoConfiguraction,@Configuration,@ConditionalOnClass 就是⾃动配置 的核⼼,⾸先它得是⼀个配置⽂件,其次根 据类路径下是否有这个类取⾃动配置。

 

4. springboot整合数据源

4.1 整合数据源

数据源即数据库中的数据,也就是springboot连接数据库 默认数据源使用的连接池Hikari。如果不想使用默认的连接池,我们可以引入第三方的连接池。如druid
(1)导入依赖

<!--加入数据源的启动依赖: springboot启动时会加载对应的自动装配类。-->
        <dependency>
            <groupId>repMaven.org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.6.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

 (2)配置数据源信息—application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

 (3)单元测试

@SpringBootTest
class ApplicationTests {

    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}

4.2  集成druid数据源

(1)引入依赖

	   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

 (2)配置文件

spring.datasource.druid.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
#初始化的个数
spring.datasource.druid.initial-size=5
# 最大活跃数
spring.datasource.druid.max-active=10
# 最大等待时间
spring.datasource.druid.max-wait=3000
# 最小的闲置个数
spring.datasource.druid.min-idle=5

(3)测试

 @Test
    void test01() {
        System.out.println(dataSource);
    }

5. springboot整合mybatis

(1)引入依赖


	<dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>

(2)修改配置文件

#指定映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml

(3)创建数据

  (1)创建实体类

@Data
public class Dept {
    private Integer id;
    private String name;
    private String address;
}

(2)在dao层中写一个简单得查询接口

@Mapper
@Component
public interface DeptDao {
    Dept findById (Integer id);
    List<Dept> findAll();
}

(3)在mapper层中写查询语句

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.DeptDao">
    <select id="findById" resultType="com.example.entity.Dept">
                select * from tb_dept where id=#{id}
    </select>
    <select id="findAll" resultType="com.example.entity.Dept">
        select * from tb_dept
    </select>

</mapper>

(4)在主启动类上加入注解

@SpringBootApplication
@MapperScan(basePackages = "com.example.dao") //为指定包下的接口生成代理实现类
public class DemoApplication {
    public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class,args);
    }

}

(5) 测试

 @Autowired
    private DeptDao deptDao;
    @Test
    void test02(){
        System.out.println(deptDao.findById(4));
    }

6. springboot整合PageHelper分页插件

(1)引入依赖

	<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.2</version>
        </dependency>

(2) 测试

 @Autowired
    private DeptDao deptDao;
    @Test
    void test03() {
        PageHelper.startPage(1,10);
        List<Dept> list = deptDao.findAll();
        PageInfo<Dept> pageInfo = new PageInfo<>(list);
        System.out.println("当前页数"+pageInfo.getPageNum());
        System.out.println("当前总页码"+pageInfo.getPages());
        System.out.println("总条数"+pageInfo.getTotal());
        System.out.println("当前页码的纪录"+pageInfo.getList());
    }

7. springboot整合swagger

swagger它是一个接口文档----用来前后端分离的一款文档。

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
     @Api:修饰整个类,描述Controller的作用
    @ApiOperation:描述一个类的一个方法,或者说一个接口
    @ApiParam:单个参数描述
    @ApiModel:用对象来接收参数
    @ApiModelProperty:用对象接收参数时,描述对象的一个字段
    @ApiImplicitParam:一个请求参数
    @ApiImplicitParams:多个请求参数

(1)引入依赖

	<dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.7.8</version>
        </dependency>

(2)创建swagger配置类


@Configuration
public class SwaggerConfig {

    @Bean //swagger中所有的功能都封装再Docket类中。
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//设置api文档信息
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) //指定为哪些包下的类生成接口文档。
                .build()
                ;

        return docket;
    }

    //定义自己接口文档信息
    private ApiInfo apiInfo() {
        Contact DEFAULT_CONTACT = new Contact("名称", "www.baidu.com", "www.baidu.com");
        ApiInfo apiInfo = new ApiInfo("CRUD", "对tb_dept表进行增删改查", "3.0T", "www.baidu.com",
                DEFAULT_CONTACT, "AAA", "www.baidu.com", new ArrayList<VendorExtension>());

        return apiInfo;
    }
}

 (3)在主启动类中开启swagger注解

(4)访问

第一种: http://localhost:8081/swagger-ui.html

第二种: http://localhost:8081/doc.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值