SpringBoot03学习笔记-狂神03

Swagger

1、Swagger简介

  • 号称世界最流行的API框架
  • RestFul API文档在线自动生成工具=>API文档与API定义同步更新
  • 直接运行,可以在线测试API接口
  • 支持多种语言(Java、PHP)

Swagger官网

在项目中使用Swagger需要springfox;

  • swagger2
  • ui

2、SpringBoot集成Swagger

1、新建springboot的web项目

2、导入相关依赖

<!--Swagger相关依赖-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

3、编写一个Hello工程

4、配置Swagger–>SwaggerConfig

package com.jian.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration
@EnableSwagger2  //开启swagger2
public class SwaggerConfig {
}

在这里插入图片描述

3、配置Swagger信息

//配置Swagger的Docket的bean实例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }

    //配置Swagger信息apiInfo
    private ApiInfo apiInfo() {
        //作者信息
        Contact DEFAULT_CONTACT = new Contact("Json", "https://www.baidu.com", "hj15170607057@163.com");
        return new ApiInfo("Json的Swagger日志",
                "加油向前冲,好好写代码,天天向上",
                "1.0",
                "urn:tos",
                DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList());

    }

4、Swagger配置扫描接口

修改Docket的bean

@Bean
public Docket docket(Environment environment) {
    //设置要显示Swagger的环境
    Profiles profiles = Profiles.of("dev");
    //通过environment.acceptsProfiles(profiles);判断是否在自己设定的环境中
    boolean flag = environment.acceptsProfiles(profiles);

    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            //是否启动swagger,false代表不启动
            .enable(flag)
            .select()
            //RequestHandlerSelectors配置要扫描接口的方式
            //basePackage(): 指定要扫描的包
            //any(): 扫描全部
            //none(): 不扫描
            //withClassAnnotation: 扫描类上的注解,参数是一个注解的反射对象
            //withMethodAnnotation: 扫描方法上的注解
            .apis(RequestHandlerSelectors.basePackage("com.jian.controller"))
            //配置允许扫描的url
            .paths(PathSelectors.ant("/**"))
            .build();
}

多环境切换

application-dev.yaml

server:
  port: 8080

application-prod.yaml

server:
  port: 8081

application.properties

spring.profiles.active=dev

SwaggerConfig

public Docket docket(Environment environment) {
    //设置要显示Swagger的环境
    Profiles profiles = Profiles.of("dev");
    //通过environment.acceptsProfiles(profiles);判断是否在自己设定的环境中
    boolean flag = environment.acceptsProfiles(profiles);

配置API文档分组

在SwaggerConfig中配置多个Docket实例实现分组groupName()

    @Bean
    public Docket docketOne() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("Anna");
    }
    @Bean
    public Docket docketTwo() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("Bob");
    }

配置实体类Model

新建一个pojo包,新建实体类User,注解@ApiModel()

package com.jian.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

//Api(注释信息)
@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

控制器,注解@ApiOperation()和@ApiParam()

package com.jian.controller;

import com.jian.pojo.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

@RestController
public class HelloController {
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello World";
    }

    //只要我们的接口中,返回值中存在实体类,它就会被扫描到Swagger中
    @PostMapping("/user")
    @ResponseBody
    public User user() {
        return new User();
    }

    @ApiOperation("helloT控制方法")
    @GetMapping("/helloT")
    public String helloT(@ApiParam("username参数") String username) {
        return username;
    }
}

总结

  1. 我们可以通过Swagger给一些比较难理解的属性或者接口,增加注释信息
  2. 接口文档实时更新
  3. 可以在线测试
  4. 注意在正式发布的时候关闭Swagger!!!出于安全考虑,节省运行的内存

任务

1、异步任务

1、添加service包,新建AsyncService类,注解**@Async**

package com.jian.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async  //告诉Spring这是一个异步方法
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }
}

2、添加controller包,新建AsyncController

package com.jian.controller;

import com.jian.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/async")
    public String hello() {
        asyncService.hello();
        return "OK";
    }
}

3、开启异步注解功能

package com.jian;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync  //开启异步注解功能
@SpringBootApplication
public class Springboot08TaskApplication {

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

}

2、邮件任务

1、导入依赖spring-boot-starter-mail

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、配置文件application.properties

spring.mail.host=smtp.qq.com
spring.mail.username=1755594680@qq.com
spring.mail.password=gtjrcourpjxreeja

3、测试简单邮件和复杂邮件发送

package com.jian;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class Springboot08TaskApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject("世界如此简单");
        message.setText("抖音,打造美好世界,欢迎观看,Come on");

        message.setFrom("1755594680@qq.com");
        message.setTo("hj15170607057@163.com");
        mailSender.send(message);
    }

    /**
     *
     * @throws MessagingException
     */
    @Test
    void contextLoads2() throws MessagingException {
        //通过mailSender创建一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        //正文
        helper.setSubject("世界这么美好");
        helper.setText("<p style='color:red'>世界真好,要努力丫</p>",true);
        //附件
        helper.addAttachment("1.png",
                new File("C:\\Users\\hj151\\Desktop\\Java学习\\img\\aop01.png"));
        helper.setFrom("1755594680@qq.com");
        helper.setTo("hj15170607057@163.com");
        mailSender.send(mimeMessage);
    }
}

3、定时任务

1、service包下编写ScheduledService类 cron表达式生成器

package com.jian.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {

    /*
    cron="秒 分 时 日 月 星期"
    cron="* * * * * *"
    */
    @Scheduled(cron = "0/10 58 20 * * ?")
    public void print(){
        System.out.println("Hello,你被执行了");
    }
}

2、开启定时任务支持注解

package com.jian;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync  //开启异步注解功能
@EnableScheduling  //开启定时任务
@SpringBootApplication
public class Springboot08TaskApplication {

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值