参考文档:Spring官网
第一步:导入jar包,和注解开发相同的jar,参考:https://blog.csdn.net/weixin_35873355/article/details/81866691
第二步,写接口和实现类:
public interface RoleService {
public void printRole(String msg);
public void printRole(String name,String sex);
}
@Component
public class RoleServiceImpl implements RoleService {
//切点
public void printRole(String name) {
System.out.println("我的名字:"+name);
}
public void printRole(String name, String sex) {
System.out.println("自己的方法"+name+""+sex);
}
}
第三步:写切面类
package com.blog.aop.xml;
/**
* 第一个切面
* @author jytpay
*
*/
public class MyAspect {
/**
* 定义advice
* @param dbName
*/
public void beforeWithMethod() {
System.out.println("before with method:");
}
public void after() {
System.out.println("after");
}
public void afterRuturning() {
System.out.println("afterRuturning");
}
public void afterThrowing() {
System.out.println("afterThrowing");
}
public void around() {
System.out.println("around");
}
}
第四步:写配置文件
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--spring-tx.xsd 这个nameSpace在spring Data里面 -->
<!-- 配置Spring自动扫描 -->
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.blog.aop"></context:component-scan>
<!-- 配置切面Bean -->
<bean name="aspectBean" class="com.blog.aop.xml.MyAspect"></bean>
<aop:config>
<!-- 2,定义切点 -->
<aop:pointcut id="myPointCut" expression="execution(* com.blog.aop.RoleServiceImpl.printRole(..))"/>
<!-- 1,定义切面 order参数:当同一个方法有多个切面时,可以通过order参数,指定执行顺序,也可以通过实现Ordered方法来实现-->
<aop:aspect id="myaspect" ref="aspectBean" order="1">
<!-- 当定义多个切面时,执行顺序使用order -->
<aop:before method="beforeWithMethod" pointcut-ref="myPointCut" />
<aop:after method="after" pointcut-ref="myPointCut"/>
<aop:after-returning method="afterRuturning" pointcut-ref="myPointCut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>
</beans>
第五步:测试类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-aop.xml");
RoleService service = (RoleService)context.getBean("roleServiceImpl");
service.printRole("张三");
}