开始

img

img

img

概述

img

开发步骤

img

img

  • application.xml
1
2
3
4
5
<bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl"></bean>

<bean id="userService" class="com.cyt.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
  1. 导坐标
1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
  1. 配置 web.xml
1
2
3
4
5
6
7
8
9
10
<!--配置spring mvc 前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup> // 自启动
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern> // 缺省
</servlet-mapping>
  1. Controller

  2. Mapping

    1. 在webapp下创建success.jsp
1
2
3
4
5
6
7
8
9
@Controller
public class UserController {

@RequestMapping("/quick")
public String save() {
System.out.println("Controller save running...");
return "success.jsp";
}
}

\5. 组件扫描 spring-mvc.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:contex="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!--Controller组件扫描-->
<contex:component-scan base-package="com.cyt.controller"/>
</beans>
  1. web.xml 添加地址
1
2
3
4
5
6
7
8
9
10
<!--配置spring mvc 前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

流程图

img

组件解析

✨✨执行流程

img

img

@RequestMapping

img

1
2
3
4
5
6
7
8
9
10
@Controller
@RequestMapping("/user")
public class UserController {

@RequestMapping(value = "/quick", method = RequestMethod.GET, params = {"username"})
public String save() {
System.out.println("Controller save running...");
return "/success.jsp";
}
}

扫描

1
2
3
4
5
6
7
<!--Controller组件扫描-->
<contex:component-scan base-package="com.cyt.controller">
<!--需要扫描的-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!--不扫瞄的-->
<!-- <context:exclude-filter type="annotation" expression=""/>-->
</contex:component-scan>

视图解析器

img

  • forward默认值 分发
  • redirect 重定向
  • 源码

img

  • spring-mvc.xml
1
2
3
4
5
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

组件和配置

img

img

✨✨数据响应

img

页面跳转

字符串形式

img

返回ModelAndView

  1. 形式1
1
2
3
4
5
6
7
8
9
10
11
12
@RequestMapping(value = "/quick2")
public ModelAndView save2() {
/*
* Model:模型 封装数据
* View: 视图 展示数据
* */
ModelAndView modelAndView = new ModelAndView();
// 设置模型数据
modelAndView.addObject("username","cyt");
modelAndView.setViewName("success");
return modelAndView;
}
  1. 形式2
1
2
3
4
5
@RequestMapping(value = "/quick3")
public ModelAndView save3(ModelAndView modelAndView) {
modelAndView.addObject("username","cyt");
modelAndView.setViewName("success");
return modelAndView;
  1. model

    1. 在域中封装数据
1
2
3
4
5
@RequestMapping(value = "/quick4")
public String save4(Model model) {
model.addAttribute("username", "cyt");
return "success";
}

回写数据

返回字符串

  1. 原始方法 不常用 注入思想
1
2
3
4
5
@RequestMapping(value = "/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().print("cyt");

}
  1. 直接返回 @ResponseBody

img

1
2
3
4
5
@RequestMapping(value = "/quick7")
@ResponseBody /*不进行页面跳转 回写数据*/
public String save7() throws IOException {
return "hello";
}

工具 返回json

  • 导包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
  • 使用
1
2
3
4
5
6
7
8
9
10
11
@RequestMapping(value = "/quick9")
@ResponseBody /*不进行页面跳转 回写数据*/
public String save9() throws IOException {
User user = new User();
user.setUsername("cyt");
user.setAge(20);
// 使用json工具
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}

✨✨框架返回对象或集合

方法一

  • 不推荐
  • 配置spring-mvc.xml
1
2
3
4
5
6
7
8
// 配置处理器映射器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
  • 测试
1
2
3
4
5
6
7
8
9
@RequestMapping(value = "/quick10")
@ResponseBody /*不进行页面跳转 回写数据*/
/*spring mvc 自动将user转换为json格式*/
public User save10() throws IOException {
User user = new User();
user.setUsername("cyt");
user.setAge(18);
return user;
}

✨方法二

  • 开发必写
  • 配置spring-mvc.xml
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--mvc注解驱动-->
<mvc:annotation-driven/>
</beans>

获得请求数据

img

分类

img

基本数据类型

img

  • int类型自动将字符串转为数字
1
2
3
4
5
6
@RequestMapping(value = "/quick11")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save11(String username, int age) throws IOException {
System.out.println("username:" + username);
System.out.println("age:" + age);
}

pojo类型

img

  • 前提:pojo对象

    • 有set get方法
    • 有toString方法
1
2
3
4
5
@RequestMapping(value = "/quick12")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save12(User user) throws IOException {
System.out.println(user);
}

获得数组

img

1
2
3
4
5
@RequestMapping(value = "/quick13")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save13(String []strs) throws IOException {
System.out.println(Arrays.asList(strs));
}

获得集合类型

法一

  • 不用
1
2
3
4
5
@RequestMapping(value = "/quick14")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save14(VO vo) throws IOException {
System.out.println(vo);
}
  • 封装VO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class VO {
private List<User> userList;

@Override
public String toString() {
return "VO{" +
"userList=" + userList +
'}';
}

public List<User> getUserList() {
return userList;
}

public void setUserList(List<User> userList) {
this.userList = userList;
}
}

✨✨@RequestBody法二

  • 前端发请求

img

  • 获取数据@RequestBody

img

  • 开放静态资源
1
2
3
4
5
<!--开放资源访问-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/img/**" location="/img/"/>
<!--或者-->
<mvc:default-servlet-handler/>

解决post乱码

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--配置全局过滤的filter-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

@RequestParam

img

  • value 将传来的参数映射
1
2
3
4
5
@RequestMapping(value = "/quick16")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save16(@RequestParam(value = "name",required = false,defaultValue = "cyt") String username) throws IOException {
System.out.println(username);
}

Restful

img

img

自定义类型转换

  • 以转换日期格式为例
  1. com.cyt.converter.DateConverter创建转换文件目录和文件
1
2
3
4
5
6
7
8
9
10
11
12
13
public class DateConverter implements Converter<String, Date> {
public Date convert(String dateStr) {
/*将日期字符串转为日期对象*/
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
  1. 声明spring-mvc.xml
1
2
3
4
5
6
7
8
<!--声明转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.cyt.converter.DateConverter"/> // 转换方法位置
</list>
</property>
</bean>

\3. 注册spring-mvc.xml

1
2
<!--mvc注解驱动-->
<mvc:annotation-driven conversion-service="conversionService"/>
  1. 使用
1
2
3
4
5
@RequestMapping(value = "/quick18")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save18(Date date) throws IOException {
System.out.println(date);
}

获得Servlet方法

img

1
2
3
4
5
6
7
8
9
10
@RequestMapping(value = "/quick19")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save19(HttpServletRequest request, HttpServletResponse resp, HttpSession session) throws IOException {
System.out.println(request);
System.out.println(resp);
System.out.println(session);
}
// org.apache.catalina.connector.RequestFacade@6d6ac1d6
// org.apache.catalina.connector.ResponseFacade@991e6af
// org.apache.catalina.session.StandardSessionFacade@7c7cf326

✨✨获取请求体

@RequestHeader

img

1
2
3
4
5
6
7
@RequestMapping(value = "/quick20")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save20(@RequestHeader(value = "User-Agent", required = false) String user_agent) throws IOException {
System.out.println(user_agent);
}
// Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X)
// AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1

@CookieValue

img

1
2
3
4
5
@RequestMapping(value = "/quick21")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
System.out.println(jsessionId); // 98B07C1D1B2C1275322F3C54A6506439
}

文件上传

原理

img

步骤

  1. 导入坐标
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
  1. spring-mvc.xml配置文件上传解析器
1
2
3
4
5
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSizePerFile" value="5000000"></property>
</bean>
  1. 编写文件上传代码
  • 页面文件 upload.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%--
Created by IntelliJ IDEA.
User: cyt
Date: 2023/3/25
Time: 21:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件<input type="file" name="uploadFile"><br/>
<input type="submit" value="提交">
</form>

</body>
</html>
  • 方法

    • 并保存到服务器
    • 参数名和jsp文件里的name属性一致
1
2
3
4
5
6
7
8
9
10
11
@RequestMapping(value = "/quick22")
@ResponseBody /*不进行页面跳转 回写数据*/
public void save22(String username, MultipartFile uploadFile) throws IOException {
System.out.println(username);
System.out.println(uploadFile);
//cyt
//org.springframework.web.multipart.commons.CommonsMultipartFile@70f7dc91
/*获得上传文件名称*/
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("D:\\" + originalFilename));
}
  1. 多个文件用数组接受

img

Spring Jdbc Template

  • 了解即可

img

概述

img

快速上手

导包

img

案例

  1. 导包
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
  1. 实体domain/Account.class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Account {
private String name;
private double money;

@Override
public String toString() {
return "Account{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getMoney() {
return money;
}

public void setMoney(double money) {
this.money = money;
}
}
  1. 方法

img

Spring 产生模板对象

img

1
2
3
4
5
6
7
8
9
10
11
<!--数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/cyt_db02"/>
<property name="user" value="root"/>
<property name="password" value="cyt"/>
</bean>
<!--jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>

练习

搭建

img

  • spring-mvc.xml
1
2
3
4
5
6
7
8
9
<!--1.mvc注解驱动-->
<mvc:annotation-driven/>
<!--2.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--静态资源开发权限-->
<mvc:default-servlet-handler/>

步骤

domain

  • Role类 get set 方法
1
2
3
private Long id;
private String roleName;
private String roleDesc;

dao

  • 接口RoleDao
1
2
3
public interface RoleDao {
List<Role> findAll();
}
  • 实现方法RoleDaoImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class RoleDaoImpl implements RoleDao {

private JdbcTemplate jdbcTemplate;

public RoleDaoImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public List<Role> findAll() {
List<Role> roleList = jdbcTemplate.query
("select * from sys_role", new BeanPropertyRowMapper<Role>(Role.class));
return roleList;
}
}

Service层

  • RoleService接口
1
2
3
public interface RoleService {
public List<Role> list();
}
  • RoleServiceImpl类
1
2
3
4
5
6
7
8
9
10
11
12
13
public class RoleServiceImpl implements RoleService {

private RoleDao roleDao;

public RoleServiceImpl(RoleDao roleDao) {
this.roleDao = roleDao;
}

public List<Role> list() {
List<Role> roleList = roleDao.findAll();
return roleList;
}
}

Controller层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Controller
@RequestMapping("/role")
public class RoleController {

@Autowired
private RoleService roleService;

public RoleController(RoleService roleService) {
this.roleService = roleService;
}

@RequestMapping("/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
// 设置模型
modelAndView.addObject("roleList", roleList);
// 设置视图
modelAndView.setViewName("role-list");
return modelAndView;
}
}

注入和配置

Controller组件扫描

  • 将上述Controller 注入到IOC容器spring-mvc.xml
1
2
3
4
xmlns:context="http://www.springframework.org/schema/context"

<!--组件扫描 扫描Controller-->
<context:component-scan base-package="com.cyt.controller"/>

Service Dao层

  • applicationContext.xml spring配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置service-->
<bean id="roleService" class="com.cyt.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
// setRoleDao
</bean>

<!--配置roleDao-->
<bean id="roleDao" class="com.cyt.dao.impl.RoleDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
// setJdbcTemplate
</bean>

拦截器

作用

img

区别

  • 了解

img

快速开始

拦截器

  • interceptor/MyInterceptor1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyInterceptor1 implements HandlerInterceptor {

// 目标方法之前执行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("prehandle..."); // 1
return false; // 返回false 后面都不执行
}

// 目标方法执行之前 视图对象执行之后
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}

// 整个流程都执行完毕后
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}

配置

  • spring-mvc.xml
1
2
3
4
5
6
7
<mvc:interceptors>
<mvc:interceptor>
<!--对哪些资源进行拦截操作-->
<mvc:mapping path="/**"/>
<bean class="com.cyt.interceptor.MyInterceptor1"/>
</mvc:interceptor>
</mvc:interceptors>

目标方法

  • contorller/TargetContoller
1
2
3
4
5
6
7
8
9
10
11
12
@Controller
public class TargetController {

@RequestMapping("/target")
public ModelAndView show() {
System.out.println("目标执行..."); // 2
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name", "cyt"); // 3
modelAndView.setViewName("index"); // 4
return modelAndView;
}
}

执行顺序

  • 先执行pre1
  • 在执行pre2
  • post2
  • post1
  • compl2
  • compl1

img

方法说明

img

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class DemoServiceImpl implements DemoService {
public void show1() {
System.out.println("抛出类型转换异常....");
Object str = "zhangsan";
Integer num = (Integer)str;
}

public void show2() {
System.out.println("抛出除零异常....");
int i = 1/0;
}

public void show3() throws FileNotFoundException {
System.out.println("文件找不到异常....");
InputStream in = new FileInputStream("C:/xxx/xxx/xxx.txt");
}

public void show4() {
System.out.println("空指针异常.....");
String str = null;
str.length();
}

public void show5() throws MyException {
System.out.println("自定义异常....");
throw new MyException();
}
}

处理思路

  • 向上抛异常
  • 主要看绿色框

img

SimpleMappingExceptionResolver

  • property 配置所有异常默认 找不到异常匹配页面显示
  • entry是匹配错误显示页面

img

自定义异常

步骤

img

  1. resolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MyExceptionResolver implements HandlerExceptionResolver {

/*
参数Exception:异常对象
返回值ModelAndView:跳转到错误视图信息
*/
public ModelAndView resolveException(HttpServletRequest
httpServletRequest,
HttpServletResponse httpServletResponse, Object o, Exception e) {


ModelAndView modelAndView = new ModelAndView();

if(e instanceof MyException){
modelAndView.addObject("info","自定义异常");
}else if(e instanceof ClassCastException){
modelAndView.addObject("info","类转换异常");
}

modelAndView.setViewName("error");

return modelAndView;
}
}
  1. spring-mvc.xml
1
2
<!--自定义异常处理器-->
<bean class="com.itheima.resolver.MyExceptionResolver"/>

AOP

介绍

  • AOP是OOP的延续

    • 个模块互不干扰 运行时动态绑定
    • 松耦合作用

img

作用及优势

img

img

动态代理

  • 了解 看懂即可

    • 开发 动态代理spring配置

JDK

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 目标对象
Target target = new Target();
// 增强对象
final Advice advice = new Advice();
// 返回值 就是动态生成的代理对象
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(), // 目标对象类加载器
target.getClass().getInterfaces(), // 目标对象相同的接口字节码对象数组
new InvocationHandler() {
// 调用代理的任何方法 实质都是invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.before(); // 前置增强
Object invoke = method.invoke(proxy, args);// 执行目标方法
advice.afterReturning(); // 后置增强
return invoke;
}
}
);
// 调用代理对象的方法
proxy.save();
}

cglib

  • 查看集成

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 目标对象
final Target target = new Target();
// 增强对象
final Advice advice = new Advice();
// 返回值 就是动态生成的代理对象 基于cglib
// 1.创建增强器
Enhancer enhancer = new Enhancer();
// 2.设置父类(目标)
enhancer.setSuperclass(Target.class);
// 3.设置回调
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
advice.before();// 执行前置
Object invoke = method.invoke(target, args);// 执行目标
advice.afterReturning();// 执行后置
return null;
}
});
// 4.创建代理对象
Target proxy = (Target) enhancer.create();
proxy.save();

✨aop相关概念

  • 连接点 可以被增强的方法叫连接点 (女朋友)
  • 切入点(老婆)
  • 通知/增强拦截连接点要做的事
  • 切面 切点加通知
  • 织入将切点和增强结合

img

快速入门

  • 3.aop底层使用哪种代理方式

    • 有接口:使用jdk
    • 没有接口:使用cglib

img

XML开发aop

img

入门

导包

  • aspectj 第三方aop实现 比spring自身的好
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>

目标接口和方法

1
2
3
4
5
6
7
8
public interface TargetInterface {
public void save();
}
public class Target implements TargetInterface {
public void save() {
System.out.println("save running....");
}
}

切面类

  • 内有增强方法
1
2
3
4
5
public class MyAspect {
public void before() {
System.out.println("前置增强");
}
}

spring配置

  • applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<!--配置目标对象-->
<bean id="target" class="com.cyt.proxy.aop.Target"></bean>
<!--配置切面对象-->
<bean id="myAspect" class="com.cyt.proxy.aop.MyAspect"></bean>
<!--配置织入 告诉spring 那些方法需要那些增强(前置,后置)-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--切面: 切点 + 通知 --> 切点表达式
<aop:before method="before" pointcut="execution(public void com.cyt.proxy.aop.
Target.save())"/>
</aop:aspect>
</aop:config>

切点表达式

  1. Target类下的method方法
  2. Target类下的任意方法 且参数任意
  3. 常用返回值任意 限定aop包下的 任意类的任意方法
  4. aop包及其子包的任意类 任意方法 参数不限
  5. all

img

1
<aop:before method="before" pointcut="execution(* com.cyt.proxy.aop.*.*(..))"/>

通知类型

img

  • 测试
  • 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MyAspect {
public void before() {
System.out.println("前置增强");
}

public void afterReturning() {
System.out.println("后置增强");
}

public Object around(ProceedingJoinPoint pjd) throws Throwable {
System.out.println("环绕前增强");
Object proceed = pjd.proceed();// 切点方法
System.out.println("环绕后增强");
return proceed;
}

public void afterThrowing() {
System.out.println("异常抛出增强...");
}

public void after() { // 无论抛不抛异常都执行
System.out.println("最终增强");
}
}
  • 配置
1
2
3
4
5
6
7
8
9
10
<aop:before method="before" pointcut="execution(* com.cyt.proxy.aop.*.*(..))"/>
<aop:after-returning method="afterReturning" pointcut="execution(* com.cyt.proxy.aop.*.*(..))"/>
<aop:around method="around" pointcut="execution(* com.cyt.proxy.aop.*.*(..))"/>
<aop:after-throwing method="afterThrowing" pointcut="execution(* com.cyt.proxy.aop.*.*(..))"/>
<aop:after method="after" pointcut="execution(* com.cyt.proxy.aop.*.*(..))"/>
前置增强
环绕前增强
save running....
最终增强
异常抛出增强...

抽取

1
2
3
4
5
6
7
8
9
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--切面: 切点 + 通知-->
<!--抽取切点表达式-->
<aop:pointcut id="myPointcut" expression="execution(* com.cyt.proxy.aop.*.*(..))"/>
<aop:after method="after" pointcut-ref="myPointcut"/>
</aop:aspect>
</aop:config>

知识要点

img

注解开发aop

img

@Component

  • target类
1
2
3
4
5
6
@Component("target") // 1
public class Target implements TargetInterface {
public void save() {
System.out.println("save running....");
}
}
  • 切面类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Component("myAspect") // 2
@Aspect /*3. 标注当前MyAspect是一个切面类*/
public class MyAspect {
// 4配置前置通知 织入
@Before("execution(* com.cyt.proxy.anno.*.*(..))")
public void before() {
System.out.println("前置增强");
}

public void afterReturning() {
System.out.println("后置增强");
}

public Object around(ProceedingJoinPoint pjd) throws Throwable {
System.out.println("环绕前增强");
Object proceed = pjd.proceed();// 切点方法
System.out.println("环绕后增强");
return proceed;
}

public void afterThrowing() {
System.out.println("异常抛出增强...");
}

public void after() { // 无论抛不抛异常都执行
System.out.println("最终增强");
}
}

配置

1
2
3
4
<!--包扫描-->
<context:component-scan base-package="com.cyt.proxy.anno"/>
<!--aop自动代理-->
<aop:aspectj-autoproxy/>

抽取

img

事务

编程式

PlatformTransactionManager(接口)

  • 不同层对应 的api实现方法不一样

img

TransactionDefinition(对象)

  • 维护事务的信息

img

隔离级别

img

传播行为

  • 了解

img

TransactionStatus

img

基于XML

介绍

  • 基于aop

img

快速入门

  1. 引入命名空间
1
xmlns:tx="http://www.springframework.org/schema/tx"
  1. applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!--包扫描-->
<context:component-scan base-package="com.cyt.proxy.anno"/>
<!--aop自动代理-->
<aop:aspectj-autoproxy/>

<!--目标对象 内部的方法就是切点-->
<bean id="UserService" class="com.cyt.service.impl.UserServiceImpl">
<property name="userDao" ref="xxx"/>
</bean>
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>


<!--1. 配置平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--2. 通知 事务的增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="xxx" isolation="DEFAULT" propagation="REQUIRED"
timeout="-1" read-only="false"/>
或者
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--3. 配置事务的aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cyt.converter.*.*(..))"/>
</aop:config>
  1. 切点方法参数配置

img

基于注解

1.

img

  1. 包扫描
  2. 注解驱动

img