创建项目
-
选择
Spring Initializr
-
选择本机配置的
JDK
-
点击
Next
-
填写
Group
-
填写
Artifact
-
选择
Maven Project
-
选择本机配置的JDK版本
-
点击
Next
-
选择
Web
-
勾选
Spring Web
-
点击
Next
-
点击
Finish
-
打开启动文件
com/example/mybatis/MybatisApplication.java
-
右键 -> run
常见问题
问题描述:
https://start.spring.io 无法访问
解决方案:
可使用 https://start.aliyun.com 替换
环境配置
配置文件支持两种写法:*.properties
和*.yml
server:
port: 8080
context-path: /
读取环境配置信息
读取单条信息
- 更改配置文件后缀
将 'resources/application.properties' 文件更改为 'application.yml'
- 添加配置
uname: 张三
- 创建控制器
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; } }
读取对象信息
- 添加配置
uconfig: uname: 张三 password: 123456
- 创建配置对象
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 }
- 创建控制器
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(); } }
读取指定配置文件的信息
- 创建配置文件
# resources/user.properties uconfig.uname=张三 uconfig.password=123456
- 创建配置对象
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 }
- 创建控制器
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
- 添加依赖
<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>
- 环境配置
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
- 创建 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>
- 创建 Mapper 接口
package com.example.mybatis.mapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface TestMapper { Integer getCount(); }
- 创建 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(); } }
- 启动并访问
打开浏览器,访问:`http://localhost:8080/`
整合 Redis
- 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.4.5.RELEASE</version> </dependency>
- 配置应用
redis: database: 0 host: 127.0.0.1 password: port: 6379
- 创建 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); } }
- 创建控制器
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. 注册阿里云账号
2. 进行实名认证
3. 开通短信服务
4. 添加签名
5. 添加模板
6. 创建 AccessKey
7. 查看AccessKey Secret - 导入依赖
<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>
- 创建短信发送配置文件
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'
- 创建短信发送配置对象
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 }
- 创建短信发送工具类
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").