必须的包,aspectjrt.jar aspectjweaver.jar cglib-nodep.jar
1.定义用户类的接口
package aopAnnotation;
public interface IUser {
/**
* 添加用户
*/
public void add();
}
2.用户接口实现类
package aopAnnotation;
public class UserImpl implements IUser {
/**
* 添加用户
*/
@Override
public void add() {
// TODO Auto-generated method stub
System.out.println("添加用户......");
}
}
3.用户实现类
package aopAnnotation;
public class UserService{
private IUser userDAO;
public void setUserDAO(IUser userDAO) {
this.userDAO = userDAO;
}
/**
* 添加用户
*/
public void save() {
userDAO.add();
}
}
4.切面类
package aopAnnotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* 切面类
* @author Administrator
*
*/
@Aspect
public class Check {
@Before("execution(public * aopAnnotation.UserService.save())")
public void checkVal(){
System.out.println("添加用户方法执行之前执行该校验方法.........");
}
}
5.spring配置文件
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 使用注解配置 -->
<context:annotation-config/>
<!-- aop自动产生动态代理配置 -->
<aop:aspectj-autoproxy/>
<!-- 服务对象配置 -->
<bean id="u" class="aopAnnotation.UserImpl"></bean>
<bean id="userService" class="aopAnnotation.UserService">
<property name="userDAO" ref="u"></property>
</bean>
<!-- 切面类配置 -->
<bean id="check" class="aopAnnotation.Check"></bean>
</beans>
6.测试类
package aopAnnotation;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AOPTest {
@Test
public void testAopAnnotation(){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)applicationContext.getBean("userService");
userService.save();
}
}
7.输出结果
添加用户方法执行之前执行该校验方法.........
添加用户......