简介
介绍

发展

快速入门


Spring配置文件
Bean

singleton 只有一个 单例
-
prototype 多例
-
1 2 3 4 5
| ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao1 = (UserDao) app.getBean("userDao"); UserDao userDao2 = (UserDao) app.getBean("userDao"); System.out.println(userDao1); System.out.println(userDao2);
|
作用范围

生命周期

1 2 3 4
| <bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl" scope="singleton" init-method="init" destroy-method="destroy">
</bean>
|
创建

无参
1 2
| <bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl" </bean>
|
工厂静态
1 2 3 4 5
| public class StaticFactory { public static UserDao getUserDao() { return new UserDaoImpl(); } }
|
1 2
| <bean id="userDao" class="com.cyt.factory.StaticFactory" factory-method="getUserDao"> </bean>
|
工厂实例
1 2 3 4 5
| public class DynamicFactory { public UserDao getUserDao() { return new UserDaoImpl(); } }
|
1 2 3
| <!--创建工厂对象--> <bean id="factory" class="com.cyt.factory.DynamicFactory"></bean> <bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>
|
依赖注入
1 2 3
| <bean id="userService" class="com.cyt.servise.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean>
|
p命名空间
1 2 3 4
| xmlns:p="http://www.springframework.org/schema/p" <bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl"> </bean> <bean id="userService" class="com.cyt.servise.impl.UserServiceImpl" p:userDao-ref="userDao"/>
|
构造方法注入
- 第一个name
userDao 是构造函数service层参数
- 第二个 ref
userDAO 是容器内部的Bean
1 2 3 4 5
| <bean id="userDao" class="com.cyt.dao.impl.UserDaoImpl"> </bean> <bean id="userService" class="com.cyt.servise.impl.UserServiceImpl"> <constructor-arg name="userDao" ref="userDao"></constructor-arg> </bean>
|
注入类型






分模块

✨✨相关API
ApplicationContext实现类✨

getBean

1 2 3
| ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao) app.getBean("userDao"); UserService bean = app.getBean(UserService.class);
|
配置数据源
数据源作用
Spring 产生数据源
1 2 3 4 5 6
| <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:/mysql://localhost:3306/test"></property> <property name="user" value="root"></property> <property name="password" value="cyt"></property> </bean>
|
抽取jdbc配置文件

1 2 3 4
| jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql: jdbc.username=root jdbc.password=cyt
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?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" 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">
<!--外部加载properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> </beans>
|
✨✨注解开发
原始注解

案例
1 2 3 4 5 6 7 8 9
|
@Repository("userDao") public class UserDaoImpl implements UserDao {
public void save() { System.out.println("save!~"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
@Service("userService") public class UserServiceImpl implements UserService {
@Autowired private UserDao userDao;
public void save() { userDao.save(); } }
|


1 2
| <!--配置组件扫描--> <context:component-scan base-package="com.cyt"></context:component-scan>
|

其他
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
|
@Service("userService") @Scope("prototype")
public class UserServiceImpl implements UserService {
@Value("${jdbc.driver}") private String driver;
@Resource(name = "userDao") private UserDao userDao;
public void save() { System.out.println(driver); userDao.save(); }
@PostConstruct public void init() { System.out.println("对象创建..."); } @PreDestroy public void destroy() { System.out.println("销毁方法..."); } }
|
新注解 AnnotationConfigApplicationContext
原始无法替代

新的


DataSourceConfiguration分数据源配置
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
| @PropertySource("classpath:jdbc.properties") public class DataSourceConfiguration { @Value("${jdbc.driver}") private String driver;
@Value("${jdbc.url}") private String url;
@Value("${jdbc.username}") private String username;
@Value("${jdbc.password}") private String password;
@Bean("dataSource") public DataSource geDataSource() throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(driver); dataSource.setJdbcUrl(url); dataSource.setUser(username); dataSource.setPassword(password); return dataSource; } }
|
SpringConfiguration 总配置文件
1 2 3 4 5 6 7 8 9 10
| @Configuration
@ComponentScan("com.cyt")
@Import({DataSourceConfiguration.class}) public class SpringConfiguration {
}
|
1 2 3 4 5
| ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class); UserService userService = app.getBean(UserService.class); userService.save();
|
Spring整合Junit
传统问题

步骤

- 导坐标
1 2 3 4 5
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.5.RELEASE</version> </dependency>
|
- 测试文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class}) public class SpringJunitTest { @Autowired private UserService userService;
@Autowired private DataSource dataSource;
@Test public void test() { userService.save(); } @Test public void test1() { System.out.println(dataSource); } }
|
Spring集成web
环境搭建
- 导坐标
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency>
|
tomcat监听器

listener/WebApplicationContextUtils
1 2 3 4 5
| public class WebApplicationContextUtils { public static ApplicationContext getWebApplicationContext(ServletContext servletContext) { return (ApplicationContext) servletContext.getAttribute("app"); } }
|
web/UserSevlet
1 2 3 4 5 6 7 8 9 10 11
| public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext); UserService userService = app.getBean(UserService.class); userService.save(); } }
|
✨✨Spring获取上下文


导入依赖
1 2 3 4 5
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.5.RELEASE</version> </dependency>
|
配置web.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
| <?xml version="1.0" encoding="UTF-8"?> <web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<!--初始化全局参数--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
<!--配置监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.cyt.web.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/userServlet</url-pattern> </servlet-mapping> </web-app>
|
web/servlet
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); ApplicationContext app = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext); UserService userService = app.getBean(UserService.class); userService.save(); } }
|
尚硅谷Spring
手写IOC

MVC复习


IOC和DI
基本介绍
IOC

DI
- 为成员变量赋值
- ioc是思想,DI是对ioc的一种实现

IOC在spring实现
查看关系


细节
- pojo对象一定要有无参构造(含有有参构造时)
- 不然报错
<init>.
获取bean的三种方式
1 2 3
| Student studentOne = (Student) ioc.getBean("studentOne"); Student bean = ioc.getBean(Student.class); Student studentOne1 = ioc.getBean("studentOne", Student.class);
|
结论
- 根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类 型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。
- 满足这个
类 或其父类 或其实现的接口
依赖注入DI
setter注入
1 2 3 4 5 6 7
| <bean id="studentTwo" class="com.cyt.spring.pojo.Student"> <property name="sid" value="1001"/> <property name="sname" value="张三"/> <property name="age" value="23"/> <property name="gender" value="男"/> </bean>
|
构造器注入
1 2 3 4 5 6
| <bean id="studentThree" class="com.cyt.spring.pojo.Student"> <constructor-arg value="1002"/> <constructor-arg value="张三"/> <constructor-arg value="23"/> <constructor-arg value="男"/> </bean>
|
特殊处理
null
1 2 3 4 5 6 7 8
| <bean id="studentTwo" class="com.cyt.spring.pojo.Student"> <property name="sid" value="1001"/> <property name="sname" value="张三"/> <property name="age" value="23"/> <property name="gender"> <null/> </property> </bean>
|
xml实体
1 2 3
|
<property name="expression" value="<王五&rt;"/>
|
CDATA
1 2 3 4 5 6 7
| <property name="expression">
<value><![CDATA[a < b]]></value> </property
|
✨为类赋值
ref引用
- student中有clazz属性(类变量)
- 从IOC容器中已有的bean赋值
1 2 3 4 5 6 7 8 9 10 11
| <bean id="studentFive" class="com.cyt.spring.pojo.Student"> <property name="sid" value="1005"/> <property name="sname" value="张三"/> <property name="age" value="25"/> <property name="gender" value="男"/> <property name="clazz" ref="clazzOne"/> </bean> <bean id="clazzOne" class="com.cyt.spring.pojo.Clazz"> <property name="cid" value="1111"/> <property name="cname" value="1班"/> </bean>
|
级联方式

内部bean
- 内部bean不能直接通过IOC获取
- 只能在bean的内部使用
1 2 3 4 5 6 7 8 9 10 11 12
| <bean id="studentFive" class="com.cyt.spring.pojo.Student"> <property name="sid" value="1005"/> <property name="sname" value="张三"/> <property name="age" value="25"/> <property name="gender" value="男"/> <property name="clazz"> 内部 <bean id="clazzInner" class="com.cyt.spring.pojo.Clazz"> <property name="cname" value="2222"/> <property name="cid" value="2222"/> </bean> </property> </bean>
|
数组
1 2 3 4 5 6 7
| <property name="hobby"> <array> <value>抽烟</value> <value>喝酒</value> <value>烫头</value> </array> </property>
|
list集合
private List<Student> students;
- 方式一
1 2 3 4 5 6 7 8 9 10 11
| <bean id="clazzOne" class="com.cyt.spring.pojo.Clazz"> <property name="cid" value="1111"/> <property name="cname" value="1班"/> <property name="students"> <list> <ref bean="studentOne"/> 引用学生类 <ref bean="studentThree"/> <ref bean="studentFive"/> </list> </property> </bean>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <bean id="clazzOne" class="com.cyt.spring.pojo.Clazz"> <property name="cid" value="1111"/> <property name="cname" value="1班"/>
<property name="students" ref="studentList"/> </bean>
<util:list id="studentList"> <ref bean="studentOne"/> <ref bean="studentTwo"/> <ref bean="studentFive"/> </util:list>
|
map结合
private Map<String, Teacher> teacherMap;
- 法一:引用teacher类 类型
1 2 3 4 5 6 7 8 9 10 11 12
| <property name="teacherMap"> <map> <entry key="111" value-ref="teacherOne"/> </map> </property>
<bean id="teacherOne" class="com.cyt.spring.pojo.Teacher"> <property name="tid" value="111"/> <property name="tname" value="111"/> </bean>
|
1 2 3 4 5
| <property name="teacherMap" ref="teacherMap"/>
<util:map id="teacherMap"> <entry key="111" value-ref="teacherOne"/> </util:map>
|
p命名空间
1 2
| <bean id="studentSix" class="com.cyt.spring.pojo.Student" p:sid="10065" p:sname="小敏" p:teacherMap-ref="teacherMap"/>
|
配置数据源
1 2 3 4 5 6 7 8
| <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> </bean>
|
1 2 3 4
| jdbc.user=root jdbc.password=cyt jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC jdbc.driver=com.mysql.cj.jdbc.Driver
|
bean作用域&生命周期
bean的作用域

1 2 3 4 5 6
| ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml"); Student student1 = ioc.getBean(Student.class); Student student2 = ioc.getBean(Student.class); System.out.println(student1.hashCode()); System.out.println(student2.hashCode());
|
如何改为多例
scope="prototype"
- 默认是
singleton 一般用的多
1 2 3 4
| <bean id="student" class="com.cyt.spring.pojo.Student" scope="prototype"> <property name="sid" value="1001"/> <property name="sname" value="张三"/> </bean>
|
bean生命周期

ConfigurableApplicationContext 是ApplicationContext的子接口其中扩展了刷新和关闭容器的功能
- 配置xml
1 2 3 4 5 6 7 8
| <bean id="user" class="com.cyt.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod"> <property name="id" value="1"/> <property name="username" value="admin"/> <property name="password" value="123456"/> <property name="age" value="20"/> </bean>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public User() { System.out.println("生命周期:1、创建对象"); }
public void setId(Integer id) { System.out.println("生命周期:2、依赖注入" + id); this.id = id; }
public void initMethod() { System.out.println("生命周期:3、初始化"); }
4. 使用
public void destroyMethod() { System.out.println("生命周期:5、销毁"); }
|
1 2 3 4 5 6 7
| @Test public void test() { ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml"); User user = ioc.getBean(User.class); System.out.println(user); ioc.close(); }
|
作用域对生命周期影响

bean的后置处理器
- bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口, 且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容 器中所有bean都会执行
- 生命周期(all)

process.MyBeanPostProcessor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class MyBeanPostProcessor implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("before"); return bean; }
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("after"); return bean; } }
|
FactoryBean
工厂bean,和之前的bean工厂不同(bean工厂是内置的)
以前的工厂对象
-
现在:
-
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个 FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是 getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都 屏蔽起来,只把最简洁的使用界面展示给我们。

1 2 3 4 5 6 7 8 9
| public class UserFactoryBean implements FactoryBean<User> { public User getObject() throws Exception { return new User(); }
public Class<?> getObjectType() { return User.class; } }
|
1
| <bean class="com.cyt.spring.factory.UserFactoryBean"/>
|
自动装配
模拟
controller 调用 service层
service 调用Dao层
- xml配置
1 2 3 4 5 6 7 8 9
| <bean id="userDao" class="com.cyt.spring.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.cyt.spring.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"/> </bean>
<bean class="com.cyt.spring.controller.UserController"> <property name="userService" ref="userService"/> </bean>
|
1 2 3 4 5 6 7 8
| public class AutowireByXMLTest { @Test public void test() { ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-autowire.xml"); UserController userController = ioc.getBean(UserController.class); userController.saveUser(); } }
|
自动装配

byType
autowire="byType"适用于该类型只有一个bean
byName 适用于有多个bean
1 2 3 4 5 6 7 8 9
| <bean id="userDao" class="com.cyt.spring.dao.impl.UserDaoImpl"></bean> <bean id="userService" class="com.cyt.spring.service.impl.UserServiceImpl" autowire="byType"> </bean>
<bean class="com.cyt.spring.controller.UserController" autowire="byType"> </bean>
|
byName

1 2 3 4 5 6 7 8 9 10 11
| <bean id="userDao" class="com.cyt.spring.dao.impl.UserDaoImpl"></bean> <bean id="userService" class="com.cyt.spring.service.impl.UserServiceImpl" autowire="byType"> </bean> <bean id="Service" class="com.cyt.spring.service.impl.UserServiceImpl" autowire="byType"> </bean>
<bean class="com.cyt.spring.controller.UserController" autowire="byName"> name </bean>
|
✨注解开发
标识组件常用注解

1 2 3
| @Controller public class UserController { }
|
1 2 3
| @Service public class UserServiceImpl implements UserService { }
|
1 2 3
| @Repository public class UserDaoImpl implements UserDao { }
|
扫描
1 2
| <context:component-scan base-package="com.cyt.spring"/>
|
spring整合时
- spring-mvc扫描控制层controller
- spring扫描除了控制层以外
包含排除
1 2 3 4 5 6 7 8 9
| <context:component-scan base-package="com.cyt.spring"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="assignable" expression="com.cyt.spring.controller.UserController"/> </context:component-scan>
|
包含(只包含)
用得少 一般直接指定具体的包
- 默认使用true(扫描所有)
- 修改为
use-default-filters="false"
- 再配置只扫描类型
1 2 3 4 5 6 7 8 9
| <context:component-scan base-package="com.cyt.spring" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
|
bean的id
在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。现在使用 注解后,每个组件仍然应该有一个唯一标识
默认情况 :类名首字母小写就是bean的id。例如:UserController类对应的bean的id就是userController。 自定义bean的id
可通过标识组件的注解的value属性设置自定义的bean的id @Service("userService")//默认为userServiceImpl public class UserServiceImpl implements UserService {}
配置别名
1 2 3
| @Controller("controller") public class UserController { }
|
@Autowired自动装配
使用
1 2
| @Autowired private UserService userService;
|
1 2
| @Autowired private UserDao userDao;
|
细节

原理



1 2 3
| @Autowired @Qualifier("userServiceImpl") private UserService userService;
|
==AOP==
代理模式

理解

动态代理

JDK动态代理
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
| public class CalculatorImpl implements Calculator { public int add(int i, int j) { int result = i + j; System.out.println("方法内部,result:" + result); return result; }
public int sub(int i, int j) { int result = i - j; System.out.println("方法内部,result:" + result); return result; }
public int mul(int i, int j) { int result = i * j; System.out.println("方法内部,result:" + result); return result; }
public int div(int i, int j) { int result = i / j; System.out.println("方法内部,result:" + result); return result; } }
|
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 37
| public class ProxyFactory { private Object target;
public ProxyFactory(Object target) { this.target = target; }
public Object getProxy() { ClassLoader classLoader = this.getClass().getClassLoader(); Class<?>[] interfaces = target.getClass().getInterfaces(); InvocationHandler h = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; try { System.out.println("日志,方法:" + method.getName() + ",参数:" + Arrays.toString(args)); result = method.invoke(target, args); System.out.println("日志,方法:" + method.getName() + ",结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("日志,方法:" + method.getName() + "方法执行完毕"); } return result; } };
return Proxy.newProxyInstance(classLoader, interfaces, h); } }
|
1 2 3 4 5 6 7 8
| @Test public void testProxy() { ProxyFactory proxyFactory = new ProxyFactory(new CalculatorImpl()); Calculator proxy = (Calculator) proxyFactory.getProxy(); proxy.add(1, 2); proxy.div(1, 0); }
|
Aop相关术语
横切关注点
非核心方法
- 对于目标方法而言
- (有哪些方法名)
- (抽取前代码的部分源代码)

通知

切面

目标&代理&连接点
- 目标:非核心业务
- 代理:代理后的目标
- 连接点:不是代码层面的(下面切入点是)

切入点

总结
面向切面关键:
- 抽取横切关注点(方法名)
- 封装到切面中(类)
- 编写通知(方法)
- 用切入点表达式(代码层面)定位到连接点(逻辑层面)
- 最终功能增强
基于注解
导入依赖
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.1</version> </dependency>
|
创建切面类
1 2 3 4 5 6 7 8 9
| @Component @Aspect public class LoggerAspect {
@Before("execution(public int com.cyt.spring.aop.annotation.CalculatorImpl.add(int,int))") public void beforeAdviceMethod() { System.out.println("LoggerAspect,前置通知"); } }
|
IOC容器管理
1 2 3
| <context:component-scan base-package="com.cyt.spring.aop.annotation"/> <!--开启基于注解的AOP--> <aop:aspectj-autoproxy/>
|
测试
1 2 3 4 5 6 7
| @Test public void testAopByAnnotation() { ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("aop-annotation.xml"); Calculator caculator = ioc.getBean(Calculator.class); caculator.add(1,1); }
|
切入点表达式
四个通知
- LoggerAspect,前置通知 add 执行完毕
- 方法内部,result:2
- LoggerAspect,返回通知 add 执行完毕 结果:2
- LoggerAspect,后置通知 add 执行完毕
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 37 38 39 40 41 42 43 44
| @Component @Aspect public class LoggerAspect {
@Pointcut("execution(* com.cyt.spring.aop.annotation.*.*(..))") public void pointcut() { }
@Before("execution(* com.cyt.spring.aop.annotation.*.*(..))") public void beforeAdviceMethod(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); System.out.println("LoggerAspect,前置通知 " + signature.getName() + " 执行完毕"); }
@AfterReturning(value = "pointcut()", returning = "result") public void afterReturningAdviceMethod(JoinPoint joinPoint, Object result) { Signature signature = joinPoint.getSignature(); System.out.println("LoggerAspect,返回通知 " + signature.getName() + " 执行完毕" + " 结果:" + result); }
@After("pointcut()") public void afterAdviceMethod(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); System.out.println("LoggerAspect,后置通知 " + signature.getName() + " 执行完毕"); }
@AfterThrowing(value = "pointcut()", throwing = "ex") public void AfterThrowingAdviceMethod(JoinPoint joinPoint,Throwable ex) { Signature signature = joinPoint.getSignature(); System.out.println("LoggerAspect,异常通知 " + signature.getName() + " 执行完毕 异常:" + ex); } }
|
执行顺序

环绕通知
ProceedingJoinPoint可执行连接点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Around("pointcut()") public Object aroundAdviceMethod(ProceedingJoinPoint joinPoint) { Object result = null; try { System.out.println("环绕通知--前置通知"); result = joinPoint.proceed(); System.out.println("环绕通知--返回通知"); } catch (Throwable e) { e.printStackTrace(); System.out.println("环绕通知--异常通知"); } finally { System.out.println("环绕通知--后置通知"); } return result; }
|

优先级
1 2 3 4 5 6 7 8 9 10 11
| @Component @Aspect @Order(1) public class ValidateAspect {
@Before("com.cyt.spring.aop.annotation.LoggerAspect.pointcut()") public void beforeMethod() { System.out.println("ValidateAspect---前置通知"); } }
|
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>
|