1.xml文件
<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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!--设置自动代理-->
<aop:aspectj-autoproxy />
<!-- 自动装箱扫描,检测注释的组件-->
<context:component-scan base-package="com.donghua.aop.annotation"></context:component-scan>
<!-- Aspect ,设置切面-->
<bean id="logAd" class="com.donghua.aop.annotation.LogAd" />
</beans>
2 定义切面
@Aspect
public class LogAd{
//expression格式 (修饰符类型?(问好代表可省略如:public)
返回值类型
全限定包名?
方法名(..) ..代表参数类型
)
@Before("execution(* *(..))")
public void before(){
System.out.println("before==========>");
}
@After("execution(public * *.save(..))")
public void after(){
System.out.println("afte==========>");
}
@AfterReturning("execution(* *(..))")
public void afterreturn(){
System.out.println("afterreturn==========>");
}
@Around("execution(* *.remove*(..))")
public void around(ProceedingJoinPoint proceed){
try{
System.out.println("around==before========>");
proceed.proceed();
System.out.println("around==after====");
}catch(Throwable e){
e.getStackTrace();
}
}
}
3 定义注释的组件
@Component("userDaoImp")
public class UserDaoImp{
public UserDaoImp(){}
public void save() {
System.out.println("save======>");
}
public void delete() {
System.out.println("delete======>");
}
public void remove() {
System.out.println("remove======>");
}
}
4.测试
public class TestAop {
private static ApplicationContext ac = new
ClassPathXmlApplicationContext("com/donghua/aop/annotation/applicationContext.xml");
@Test
public void testaop(){
UserDaoImp user = (UserDaoImp) ac.getBean("userDaoImp");
System.out.println(user.getClass());
user.delete();
user.save();
user.remove();
}
}
结果:
class com.donghua.aop.annotation.UserDaoImp$$EnhancerByCGLIB$$1cb1e29b
before==========>
delete======>
afterreturn==========>
before==========>
save======>
afte==========>
afterreturn==========>
before==========>
around==before========>
remove======>
around==after====
afterreturn==========>