JAVA中 SpringBoot 的创建 以及各种短信以及邮件和Swagger的整合(开发工具:IDEA2020)

本文详细介绍了如何在Java的SpringBoot项目中创建应用,并逐步整合MyBatis、Redis、阿里云短信服务、微信登录、阿里云OSS、支付宝支付、FastDFS、MongoDB、邮件发送和Swagger2。每个整合部分都包含线上操作步骤、配置文件、工具类和控制器的创建。
摘要由CSDN通过智能技术生成

创建项目

  1. 选择 Spring Initializr

  2. 选择本机配置的 JDK

  3. 点击 Next
    在这里插入图片描述

  4. 填写 Group

  5. 填写 Artifact

  6. 选择 Maven Project

  7. 选择本机配置的JDK版本

  8. 点击 Next
    在这里插入图片描述

  9. 选择 Web

  10. 勾选 Spring Web

  11. 点击 Next
    在这里插入图片描述

  12. 点击 Finish
    在这里插入图片描述

  13. 打开启动文件

    com/example/mybatis/MybatisApplication.java
    
  14. 右键 -> run

常见问题

问题描述:
    https://start.spring.io 无法访问
解决方案:
    可使用 https://start.aliyun.com 替换

环境配置

配置文件支持两种写法:*.properties*.yml

server:
  port: 8080
  context-path: /

读取环境配置信息

读取单条信息

  1. 更改配置文件后缀
    将 'resources/application.properties' 文件更改为 'application.yml'
    
  2. 添加配置
    uname: 张三
    
  3. 创建控制器
    package com.demo.controller;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class TestController {
         
    
        @Value("${uname}")
        private String uname;
    
        @RequestMapping("/")
        @ResponseBody
        public String test(){
         
            return uname;
        }
    }
    

读取对象信息

  1. 添加配置
    uconfig:
    uname: 张三
    password: 123456
    
  2. 创建配置对象
    package com.demo.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.io.Serializable;
    
    @ConfigurationProperties(prefix = "uconfig")
    @Component
    public class UConfig implements Serializable {
         
        private String uname;
        private String password;
    
        // 省略 getter/setter
    }
    
  3. 创建控制器
    package com.demo.controller;
    
    import cn.est.config.UConfig;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.annotation.Resource;
    
    @Controller
    public class TestController {
         
    
        @Resource
        private UConfig uConfig;
    
        @RequestMapping("/")
        @ResponseBody
        public String test(){
         
            return uConfig.getUname() + " : " + uConfig.getPassword();
        }
    }
    

读取指定配置文件的信息

  1. 创建配置文件
    # resources/user.properties
    uconfig.uname=张三
    uconfig.password=123456
    
  2. 创建配置对象
    package cn.est.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    import java.io.Serializable;
    
    @ConfigurationProperties(prefix = "uconfig")
    @PropertySource("classpath:user.properties")
    @Component
    public class UConfig implements Serializable {
         
        private String uname;
        private String password;
    
        // 省略 getter/setter
    }
    
  3. 创建控制器
    package com.demo.controller;
    
    import cn.est.config.UConfig;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.annotation.Resource;
    
    @Controller
    public class TestController {
         
    
        @Resource
        private UConfig uConfig;
    
        @RequestMapping("/")
        @ResponseBody
        public String test(){
         
            return uConfig.getUname() + " : " + uConfig.getPassword();
        }
    }
    

注意事项

@PropertySource 注解不支持 yml 配置文件,只支持 property 配置文件。如果希望 @PropertySource 支持 property 配置文件,需要对该注解进行重写。

如果读取 property 配置文件中的中文为乱码,请进行如下设置:
File -> Settings -> Editor -> File Encodings -> Properties Files(*.properties) -> 选择 UTF-8,并勾选后面的复选框

整合 MyBatis

  1. 添加依赖
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>
    
  2. 环境配置
    spring:
        datasource:
            url: jdbc:mysql://localhost:3306/est?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
            driver-class-name: com.mysql.cj.jdbc.Driver
            username: root
            password: ok
    
    mybatis:
        mapper-locations: classpath:mapper/*.xml
    
  3. 创建 Mapper 映射
    <!-- resources/mapper/TestMapper.xml -->
    <?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.mybatis.mapper.TestMapper">
        <select id="getCount" resultType="int">
            SELECT COUNT(1) FROM users
        </select>
    </mapper>
    
  4. 创建 Mapper 接口
    package com.example.mybatis.mapper;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    
    @Mapper
    public interface TestMapper {
         
        Integer getCount();
    }
    
  5. 创建 controller
    package com.example.mybatis.controller;
    
    import com.example.mybatis.mapper.TestMapper;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    public class TestController {
         
        @Resource
        private TestMapper test;
    
        @RequestMapping("/")
        public Integer test(){
         
            return testMapper.getCount();
        }
    }
    
  6. 启动并访问
    打开浏览器,访问:`http://localhost:8080/`
    

整合 Redis

  1. 引入依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-redis</artifactId>
        <version>1.4.5.RELEASE</version>
    </dependency>
    
  2. 配置应用
    redis:
        database: 0
        host: 127.0.0.1
        password:
        port: 6379
    
  3. 创建 Redis 工具类
    package com.example.redis.utils;
    
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    
    @Component
    public class RedisUtils {
         
        @Resource
        private StringRedisTemplate stringRedisTemplate;
    
        /**
        * 写入数据
        *
        * @param k 键
        * @param v 值
        */
        public void set(String k, String v) {
         
            stringRedisTemplate.opsForValue().set(k, v);
        }
    
        /**
        * 写入临时数据
        * @param k 键
        * @param v 值
        * @param t 有效期,单位:秒
        */
        public void set(String k, String v, long t) {
         
            stringRedisTemplate.opsForValue().set(k, v, t, TimeUnit.SECONDS);
        }
    
        /**
        * 获取数据
        *
        * @param k 键
        * @return 值
        */
        public String get(String k) {
         
            return stringRedisTemplate.opsForValue().get(k);
        }
    }
    
  4. 创建控制器
    package com.example.redis.controller;
    
    import com.example.redis.utils.RedisUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.annotation.Resource;
    
    @Controller
    public class RedisController {
         
        @Resource
        private RedisUtils redisUtils;
    
        @ResponseBody
        @RequestMapping("/")
        public String test() {
         
            redisUtils.set("name", "张三");
            return "success";
        }
    }
    

整合 阿里云短信

  1. 阿里云短信线上操作
    1. 注册阿里云账号
    2. 进行实名认证
    3. 开通短信服务
    4. 添加签名
    5. 添加模板
    6. 创建 AccessKey
    7. 查看AccessKey Secret
  2. 导入依赖
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.5.3</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.50</version>
    </dependency>
    
  3. 创建短信发送配置文件ssm.properties
    sms.accessKeyId=此处替填写'AccessKey ID'
    sms.secret=此处填写'AccessKey Secret'
    sms.RegionId=cn-hangzhou
    sms.domain=dysmsapi.aliyuncs.com
    sms.version=2017-05-25
    sms.action=SendSms
    sms.signName=此处替换为'签名名称'
    sms.templateCode=此处替换为'模版CODE'
    
  4. 创建短信发送配置对象
    package com.example.aliyunssm.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = "sms")
    @PropertySource("classpath:ssm.properties")
    public class AliyunSSMConfig {
         
        private String accessKeyId;
        private String secret;
        private String RegionId;
        private String domain;
        private String version;
        private String action;
        private String signName;
        private String templateCode;
    
        // 省略getter/setter
    }
    
  5. 创建短信发送工具类
    package com.example.aliyunssm.utils;
    
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.CommonRequest;
    import com.aliyuncs.CommonResponse;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.http.MethodType;
    import com.aliyuncs.profile.DefaultProfile;
    import com.example.aliyunssm.config.AliyunSSMConfig;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    
    /**
    * 短信发送工具类
    */
    @Component
    public class AliyunSSMUtils {
         
    
        @Resource
        private AliyunSSMConfig aliyunSSMConfig;
    
        /**
        * 发送短信的方法
        *
        * @param phone 接收短信的手机号
        * @param code  验证码
        * @return
        */
        public boolean sendMessage(String phone, String code) {
         
    
            DefaultProfile profile = DefaultProfile.getProfile(aliyunSSMConfig.getRegionId(), aliyunSSMConfig.getAccessKeyId(), aliyunSSMConfig.getSecret());
            IAcsClient client = new DefaultAcsClient(profile);
    
            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain(aliyunSSMConfig.getDomain());
            request.setSysVersion(aliyunSSMConfig.getVersion());
            request.setSysAction(aliyunSSMConfig.getAction());
            request.putQueryParameter("RegionId", aliyunSSMConfig.getRegionId());
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", aliyunSSMConfig.getSignName());
            request.putQueryParameter("TemplateCode", aliyunSSMConfig.getTemplateCode());
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
    
            try {
         
                CommonResponse response = client.getCommonResponse(request);
                System.out.println(response.getData());
    
                String status = JSONObject.parseObject(response.getData()).get("Code").
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值