SpringBoot给我们带来了什么?
未来
spring全家桶,社区完善,用心做框架
SpringBoot环境搭建
- 依赖配置(gradle)
bulid.gradle
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.3.1.RELEASE'
- 填写主启动类
/**
* @author m_long
* @date 2020/7/23 10:40 下午
*
* SpringBootApplication
* 关键注解,表示当前类是工程的启动类且会基于此类找到包,作为扫描的根
*
*
*/
@SpringBootApplication
public class BasicApplication {
public static void main(String[] args) {
// 运行的主要类,将启动类作为第一个参数,后面跟着启动参数
SpringApplication.run(BasicApplication.class, args);
}
}
- 添加测试控制器
@RestController
public class PingController {
@RequestMapping("/ping")
public String ping(){
return "pong" + LocalDateTime.now();
}
}
- 运行main函数,浏览器输入:http://127.0.0.1:8080/ping
成功
另一种启动方式
- bulid bulid
微服务有啥缺点
运维成本在增加,你拆分了很多服务,部署成本;-springboot解决了一些;
扩容机器
老生常谈之MVC
Model View Controller
@Controller
- 拦截器,过滤器的处理(安全,登陆。。。)
- 参数校验(通用的参数校验,与业务关联不大)
- amount(金额) ===》 金额大于0
- orderId 通用校验,除了非空之外, 那么所有业务都需要长度必须为32位, 可以放在controller层来做处理。
- 业务层校验,比如支付限制最小支付金额必须大于10块。 --> 放到业务层去处理
- access log, cost time
- 处理service代码时,在controller来做统一的异常处理
- 做统一的流量收集。
- 做统计,PV,UV
- 参数校验(通用的参数校验,与业务关联不大)
-
@Service
- 真正的处理业务逻辑,
- 完成我们业务需求的绝大多数的能力都在这里做的。
- 要做好业务异常的处理(订单状态不对,订单不存在,支付金额不足)
- 做好业务拆分和设计,将各自的能力界定好边界。
- 调外部服务。。。=> 支付宝|微信 ,
-
@Repository
- 简单: 数据库的增改查。没有删除
SpringBoot参数接受
- @RequestParam
- @PathVariable
- @RequestBody & @ResponseBody
active profile 配置
- No active profile set, falling back to default profiles: default
- 一般用于多套环境支持。如: application-dev.yml,application-test.yml
- 指定profile启动
+ java -jar target/libs/springboot-1.0.0-SNAPSHOT.jar --spring.profiles.active=dev
SpringBoot常见web配置:Servlet–废弃
- 自己实现HttpServlet类,并覆写方法 doGet或doPost
- 将此类标识成@WebServlet, 名字随意起
- 在启动类上添加包扫描路径即可,@ServletComponentScan
SpringBoot常见web配置:拦截器(已登录场景为例)
- 1.实现HandlerInterceptor接口完成自己的拦截器业务编写
- 2.在配置类实现接口WebMvcConfigurer,在addInterceptors方法中添加自己的拦截器
- 注: 要么自己new HandlerInterceptor,或者标识成@Component让SpringBoot来注入
- 思考下:如果给特定的方法加上拦截器处理?
SpringBoot常见web配置:过滤器
- 配置方式:
- 方式一: 使用@WebFilter
- 创建过滤器,实现接口Filter
- 标识注解: @WebFilter(filterName = “xxxFilter”, urlPatterns = “/**”)
- 实现doFilter方法
- 在配置类中添加注解: @ServletComponentSca
- 方式一: 使用@WebFilter