1、引入jar包或者依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、使用配置文件注册类,配置切点、切面
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<bean id="user" class="homework.spring.pojo.User">
</bean>
<bean id="userDao" class="homework.spring.dao.impl.UserDaoImpl">
</bean>
<bean id="userService" class="homework.spring.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!--注册前置方法-->
<bean id="methodBefore" class="homework.spring.advise.MethodBefore"></bean>
<!-- AOP-->
<aop:config>
<!-- 配置切点-->
<aop:pointcut id="pointcut" expression="execution(* homework.spring.service..*.*(..))"/>
<!-- 配置切面类-->
<aop:advisor advice-ref="methodBefore" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
3、编写切入类
public class MethodBefore implements MethodBeforeAdvice {
/**
* 前置通知类
* @param method 切点的方法对象
* @param objects 接受的实参的数组
* @param o 切点的真实对象
*/
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("执行的对象是"+o);
System.out.println("执行的对象的方法是"+method.getName());
System.out.println("执行的对象的参数列表是"+ Arrays.toString(objects));
System.out.println("前置方法执行完毕");
}
}
4、测试
@Test
public void testUser(){
//创建容器
ApplicationContext app = new ClassPathXmlApplicationContext("ApplicationContext.xml");
userService = (UserService)app.getBean("userService");
user = (User)app.getBean("user");
user.setName("张三");
userService.save(user);
}
还有一种就是自己自定义配置类,不去实现自带的。不过要手动在配置类里标明切入时间和方法
配置文件
<!--引入目标对象:即要被增强的对象-->
<bean id="target" class="com.execrise.aop.Target"></bean>
<!--引入切面对象:增强的对象-->
<bean id="myAspect" class="com.execrise.aop.MyAspect"></bean>
<!--配置织入:告诉spring,具体有哪些方法(切点)需要哪些增强方法(通知)-->
<aop:config>
<!--声明切面:切面 = 切点 + 通知-->
<aop:aspect ref="myAspect">
<!--抽取切点表达式-->
<aop:pointcut id="mypoint" expression="execution(public void com.execrise.aop.Target.save())"/>
<!--切面-->
<!--<aop:before method="before" pointcut="execution(public void Target.save())"></aop:before>-->
<aop:before method="before" pointcut-ref="mypoint" ></aop:before>
</aop:aspect>
</aop:config>
自定义配置类
public class MyAspect {
public void before(){
System.out.println("前置方法执行了。。。");
}
public void after(){
System.out.println("后置方法执行了。。。");
}
}
测试方法
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
结果如下