这里使用ProxyFactoryBean代理实例,ProxyFactoryBean常用可配置属性如下:
1.导入JAR包
这里再导入包的时候,不仅要导入基础spring框架的基础jar包和依赖包,还要导入aopalliance-1.0.jar和spring-aop-4.3.6.RELEASE.jar
2.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="userDao" class="com.wx.dao.impl.UserDaoImpl" />
<bean id="myAspect" class="com.wx.aspect.MyAspect"/>
<!-- org\springframework\aop\framework\ProxyFactoryBean.class -->
<bean id="userDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 指定代理对象实现的接口 -->
<property name="proxyInterfaces" value="com.wx.dao.UserDao"/>
<!-- 指定目标对象 -->
<property name="target" ref="userDao"/>
<!-- 指定切面 -->
<property name="interceptorNames" value="myAspect"/>
<!-- 指定代理方式,true为cglib方式,默认jdk方式 -->
<property name="proxyTargetClass" value="true"></property>
</bean>
</beans>
3. 书写代码
package com.wx.dao;
public interface UserDao {
public void say();
}
package com.wx.dao.impl;
import com.wx.dao.UserDao;
public class UserDaoImpl implements UserDao {
@Override
public void say() {
// TODO Auto-generated method stub
//https://mvnrepository.com/artifact/aopalliance/aopalliance/1.0
System.out.println("UserService Method!");
}
}
package com.wx.aspect;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAspect implements MethodInterceptor {
public void check(){
System.out.println("check()");
}
public void log(){
System.out.println("log()");
}
@Override
public Object invoke(MethodInvocation arg0) throws Throwable {
// TODO Auto-generated method stub
check();
Object obj = arg0.proceed();
log();
return obj;
}
}
4.测试类
package com.wx.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.wx.dao.UserDao;
public class MyTest {
public static void main(String[] agrs){
ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)application.getBean("userDaoProxy");
userDao.say();
}
}
5. 结果