spring注解方式实现AOP的前置通知

spring面向切面(AOP)编程,spring的配置文件中需要引入AOP命名空间:
<?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">
</beans>
spring框架进行AOP编程的时候,spring提供了两种切面声明方式,
1、基于XML配置的方式进行AOP开发。
2、基于注解方式进行AOP开发。
<!--
打开配置项,这个配置项是对@Aspectj这个注解进行支持 注解本身是不能干活的,注解之所以能干活是

因为后面有处理器对其进行处理
这个配置相当于我们将要使用的@Aspectj注解提供了解析的功能
-->
<aop:aspectj-autoproxy />

1、新建业务bean用于测试,PersonService.java
package com.sample.service;

public interface PersonService {
public String getPersonName(Integer Id);

public void save(String userName);

public void update(String userName, Integer Id);
}
2、PersonServiceBeean.java
package com.sample.service.impl;

import com.sample.service.PersonService;

public class PersonServiceBean implements PersonService {

@Override
public String getPersonName(Integer Id) {
System.out.println("我是getPersonName()方法");
return "XXX";
}

@Override
public void save(String userName) {
System.out.println("我是save()方法");
}

@Override
public void update(String userName, Integer Id) {
System.out.println("我是update()方法");
}

}
3、基于注解方式的声明切面
package com.sample.service;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class MyInterceptor {

@Pointcut("execution (* com.sample.service.impl.PersonServiceBean..*.*(..))")
private void anyMethod() {
}// 声明一个切入点

@Before("anyMethod()")
public void doAccessCheck(String name) {
System.out.println("前置通知:" + name);
}

}

4、一定要将业务bean和切面配置在spring容器中(applicationContext.xml)中、也可以自动扫描
<bean id="myInterceptor" class="com.sample.service.MyInterceptor" />
<bean id="personService"
class="com.sample.service.impl.PersonServiceBean">
</bean>
这里也看采用spring的自动扫描交由spring容器管理bean
<context:component-scan base-package="com.sample.*"/>


@Test public void interceptorTest() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save("jack");
}


前置通知:jack
我是save()方法

猜你喜欢

转载自liangyuxiang.iteye.com/blog/2084336