1.导包:
2.目标类
package oyb.service; public interface UserService { public void add(); public void update(); public void delete(); }
package oyb.service.impl; import oyb.service.UserService; public class UserServiceImpl implements UserService { @Override public void add() { System.out.println("添加用户。。。。"); } @Override public void update() { System.out.println("更新用户。。。。"); } @Override public void delete() { System.out.println("删除用户"); } }
切面类
package oyb.aspect; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class MyAspect implements MethodInterceptor { @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { //放行 Object obj = methodInvocation.proceed(); return obj; } }
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" 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"> <!--业务类--> <bean id="userService" class="oyb.service.impl.UserServiceImpl"></bean> <!--切面类--> <bean id="myAspect" class="oyb.aspect.MyAspect"></bean> <!--使用工厂bean创建代理--> <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <!--interfaces,确定接口,多个接口用array,单个接口用value--> <property name="interfaces" value="oyb.service.UserService"></property> <!--确定目标类,--> <property name="target" value="userService"></property> <!--通知,切面类,他是一个数组--> <property name="interceptorNames" value="myAspect"></property> <!--使用cglib代理--> <!--默认使用jdk,如果声明为true的话,不论有没有接口都使用cglib代理--> <property name="optimize" value="true"></property> </bean> </beans>