初识SpringBoot--2

目录

1.SpringBoot的自动装配原理

2.springboot整合数据源

2.1 集成druid数据源

3.springboot整合mybatis

4.springboot整合PageHelper分页插件

5.springboot整合swagger2

 6.举一个栗子

6.1 结果展示

 6.2 代码框架

 6.3 各部分代码展示

扫描二维码关注公众号,回复: 14442321 查看本文章

6.3.1 SwaggerConfig类

6.3.2 controller层

6.3.3 dao包下

6.3.4 entity类

6.3.5 CommonResulet类

2.6.6 SwaggercurdApplication启动类

2.6.7 SwaggercurdApplicationTests

2.6.8 mapper层下


1.SpringBoot的自动装配原理

        什么是自动装配?

无需手动加载某些配置,而由Springboot自动加载进来。

譬如: 自己加载DispatcherServlet.

        如何完成自动装配?

 

 

 

 为什么总的自动装配类由127个。因为这些自动装配类都在某个文件中写死了。

DispatcherServlet如何完成自动装配。

2.springboot整合数据源

即是: springboot框架连接数据库。

(1)引入依赖

 <!--加入数据源的启动依赖: springboot启动时会加载对应的自动装配类。-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </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=root

(3)测试

//若是相同位置则无需使用启动类.class这一配置说明
@SpringBootTest(classes = 启动类.class)
class Qy151SpringbootApplicationTests {


    @Resource
    private DataSource dataSource;

    @Test
    public void test01() throws SQLException {
        //验证了springboot可以帮你完成数据源的自动装配功能
        System.out.println(dataSource.getConnection());
    }

}

上面默认这个数据源使用的连接池Hikari。如果不想使用默认的连接池,我们可以引入第三方的连接池。

2.1 集成druid数据源

(1)依赖

 <!--引入数据库连接池druid-->
        <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=root
#初始化的个数
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)测试

  @Resource
    private DataSource dataSource;

    @Test
    public void test01() throws SQLException {
        //验证了springboot可以帮你完成数据源的自动装配功能
        System.out.println(dataSource);
        System.out.println(dataSource.getConnection());
    }

3.springboot整合mybatis

(1)引入mybatis启动依赖类

        <!--引入mybatis的启动依赖-->
        <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)在主启动类加上注解

@SpringBootApplication
@MapperScan(basePackages = "com.ykq.dao") //为指定的包下的接口生成代理实现类
public class Qy151SpringbootApplication {

    public static void main(String[] args) {
        //加载那含有@SpringBootApplication注解的类,它的特殊之处就是该类使用了@SpringBootApplication ,它是一个复合组件。
        //@EnableAutoConfiguration
        SpringApplication.run(Qy151SpringbootApplication.class, args);
    }

}

(4)测试

   @Autowired
    private DeptMapper deptMapper;

    @Test
    public void test02(){
        System.out.println(deptMapper.findById(1));
    }

4.springboot整合PageHelper分页插件

(1)引入依赖

  <!--pageHelper的启动依赖 自动装配拦截器-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.2</version>
        </dependency>

(2)测试:

  @Test
    public void test03(){
         PageHelper.startPage(1, 3);
        List<Dept> list = deptMapper.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());

    }

5.springboot整合swagger2

什么是swagger2?

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

(1)引入swagger依赖


        <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)
                                .host("localhost:8888")
                                .apiInfo(apiInfo())//设置api文档信息
                                .select()
                                .apis(RequestHandlerSelectors.basePackage("com.qy151wd.springboot.controller"))
                                .build();

        return docket;
    }


//定义自己接口文档信息
    private ApiInfo apiInfo(){
        Contact DEFAULT_CONTACT = new Contact("小可", "http://www.baidu.com", "[email protected]");
        ApiInfo apiInfo = new ApiInfo("wd的小项目", "适合小新手", "V1.0", "http://www.jd.com",
                DEFAULT_CONTACT, "牛牛公司", "http://www.taobao.com", new ArrayList<VendorExtension>());
    return apiInfo;
    }
}

(3)开启swagger注解

//@SpringBootApplication(scanBasePackageClasses = {"指定要扫的包",“抛弃默认的扫包路径”})
@SpringBootApplication
@MapperScan(basePackages = "com.qy151wd.springboot.dao")//为指定的包下的接口生成代理实现类
@EnableSwagger2//开启swapper注解
public class SpringbootApplication {

    //加载含有@SpringBootApplication注解的类
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

(4)使用swagger注解

@Api  接口类的注解---接口类上 tag属性
@ApiOperation  接口方法的注解---接口方法上 value:
@ApiImplicitParams( 接口参数的说明
    {
      ApiImplicitParam() //单个参数的说明
    }
)

@ApiModel---- 实体类接口注解
@ApiModelProperty---->实体类属性的说明

(5)访问

注意访问的是此处:

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

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

 6.举一个栗子

关于一个数据库表的curd

6.1 结果展示

 6.2 代码框架

 6.3 各部分代码展示

6.3.1 SwaggerConfig类

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .host("localhost:8888")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.qy151wd.controller"))
                .build();
        return docket;
    }

    private ApiInfo apiInfo(){
        Contact DEFAULT_CONTACT = new Contact("孟一", "http://www.baidu.com", "[email protected]");
        ApiInfo DEFAULT = new ApiInfo("wd的一个亿的小项目", "有梦想一起实现", "V1.0", "urn:tos",
                DEFAULT_CONTACT, "牛牛公司", "http://www.taobao.com", new ArrayList<VendorExtension>());
        return DEFAULT;
    }
}

6.3.2 controller层

@RestController
@Api(tags = "Dept对应的接口")
public class DeptController {
    @Resource
    private DeptMapper mapper;

    @GetMapping("findById")
    @ApiOperation(value = "通过Id查询")
    public CommonResult findById(int id){
        Dept byId = mapper.findById(id);
        return new CommonResult(2000,"成功",byId);
    }

    @GetMapping("findAll")
    @ApiOperation(value = "查询全部")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name="pageNum",value = "页码",required = true,defaultValue = "1"),
                    @ApiImplicitParam(name="pageSize",value = "数据",required = true,defaultValue = "3"),
            }
    )
    public CommonResult findAll(int pageNum,int pageSize){
        PageHelper.startPage(1,3);
        List<Dept> all = mapper.findAll();
        PageInfo<Dept> pageInfo=new PageInfo<>(all);
        return new CommonResult(2000,"成功",pageInfo);
    }

    @GetMapping("insert")
    @ApiOperation(value = "添加元素")
    public CommonResult insert(Dept dept){
        int insert = mapper.insert(dept);
        return new CommonResult(2000,"成功",insert);
    }

    @GetMapping("update")
    @ApiOperation(value = "修改数据")
    public CommonResult update(Dept dept){
        int update = mapper.update(dept);
        return new CommonResult(2000,"成功",update);
    }

    @GetMapping("deleteId")
    @ApiOperation(value = "删除数据")
    public CommonResult deleteId(int id){
        int i = mapper.deleteId(id);
        return new CommonResult(2000,"成功",i);
    }
}

6.3.3 dao包下

public interface DeptMapper {
    public Dept findById(Integer id);

    public List<Dept> findAll( );

    public int insert(Dept dept);

    public int update(Dept dept);

    public int deleteId(Integer id);
}

6.3.4 entity类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
    private Integer id;

    private String name;

    private String realname;
}

6.3.5 CommonResulet类

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "统一的json数据")
public class CommonResult {
    @ApiModelProperty(value = "状态码,2000代表正确,5000代表失败")
    private Integer code;
    @ApiModelProperty(value = "响应的信息内容")
    private String msg;
    @ApiModelProperty(value = "响应的数据")
    private Object data;
}

2.6.6 SwaggercurdApplication启动类

@SpringBootApplication
@MapperScan(value = "com.qy151wd.dao")
@EnableSwagger2
public class SwaggercurdApplication {

    public static void main(String[] args) {
        SpringApplication.run(SwaggercurdApplication.class, args);
    }

}

2.6.7 SwaggercurdApplicationTests

@SpringBootTest
class SwaggercurdApplicationTests {

    @Test
    void contextLoads() {
    }

    @Resource
    private DeptMapper deptMapper;
    @Test
    public void findById(){
        System.out.println(deptMapper.findById(7));
    }

    @Test
    public void findAll(){
        System.out.println(deptMapper.findAll());
    }

    @Test
    public void insert(){
        System.out.println(deptMapper.insert(new Dept(null, "轮滑社", "肖可可")));
    }

    @Test
    public void update(){
        System.out.println(deptMapper.update(new Dept(25, "社联部", null)));
    }

    @Test
    public void delete(){
        System.out.println(deptMapper.deleteId(26));
    }

}

2.6.8 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.qy151wd.dao.DeptMapper">
    <sql id="resignDept">
        id,name,realname
    </sql>
    <select id="findById" resultType="com.qy151wd.entity.Dept">
        select <include refid="resignDept"/> from tb_dept where id=#{id}
    </select>
    <select id="findAll" resultType="com.qy151wd.entity.Dept">
        select <include refid="resignDept"/> from tb_dept
    </select>
    <insert id="insert" parameterType="com.qy151wd.entity.Dept">
        insert into tb_dept values (null,#{name},#{realname})
    </insert>
    <update id="update" parameterType="com.qy151wd.entity.Dept">
        update tb_dept
        <set>
            <if test="name !=null and name !=''">
                name=#{name},
            </if>
            <if test="realname !=null and realname !=''">
                realname=#{realname}
            </if>
        </set>
        where id=#{id}
    </update>
    <delete id="deleteId" parameterType="int">
        delete from tb_dept where id=#{id}
    </delete>
</mapper>

猜你喜欢

转载自blog.csdn.net/qq_50896786/article/details/125944828
今日推荐