步骤一:创建JavaWEB项目,引入具体的开发的jar包
* 先引入Spring框架开发的基本开发包
* 在引入Spring框架的AOP的开发包
* aspectJ的开发包
步骤二:创建Spring的配置文件,引入具体的AOP的schema约束
<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">
</beans>
步骤三:创建包结构,编写具体的接口和实现类
* com.jadan.demo1
> CustomerDao --- 接口
> CustomerDaoImpl --- 实现类
public interface CustomerDao {
public void save();
public void update();
}
public class CustomerDaoImpl implements CustomerDao {
public void save() {
System.out.println("保存客户...");
}
public void update() {
System.out.println("修改客户...");
}
}
步骤四:将目标类配置到Spring中
<bean id="customerDao" class="com.jadan.demo1.CustomerDaoImpl"></bean>
步骤五:定义切面类
* 添加切面和通知的注解
> @Aspect ---- 定义切面类的注解
> 通知类型(注解的参数是切入点的表达式)
* @Before ---- 前置通知
* @AfterReturning ---- 后置通知
* @Around ---- 环绕通知
* @After ---- 最终通知
* @AfterThrowing ---- 异常抛出通知
* 具体代码如下:
/**
* 注解方式的切面类
* @author Administrator
*/
@Aspect
public class MyAspectAnno {
/**
* 通知类型:
* @Before: 前置通知(切入点的表达式)
*/
@Before(value="execution(public * com.jadan.demo1.CustomerDaoImpl.save())")
public void log() {
System.out.println("记录日志...");
}
}
步骤六:在配置文件中定义切面类
<!-- 配置切面类 -->
<bean id="myAspectAnno" class="com.jadan.demo1.MyAspectAnno"></bean>
步骤七:在配置文件中开启自动代理
<!-- 开启自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
applicationContext.xml的综上配置:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启自动代理 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 配置目标对象 -->
<bean id="customerDao" class="com.jadan.demo1.CustomerDaoImpl"></bean>
<!-- 配置切面类 -->
<bean id="myAspectAnno" class="com.jadan.demo1.MyAspectAnno"></bean>
</beans>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {
@Resource(name="customerDao")
private CustomerDao customerDao;
@Test
public void run1() {
customerDao.save();
customerDao.update();
}
}