Spring漫笔-ProxyFactoryBean

Spring随笔-ProxyFactoryBean

Spring随笔-ProxyFactoryBean

   项目要用到对于权限的控制。想到SpringAOP比较适合,所以翻阅了下Spring的原文档。发现了个ProxyFactoryBean。与大家分享下。

       看这个类的名称第一感觉就是代理模式的应用。关于代理模式以后会写出来,这里不多说。在原文档中提到:如果有接口则要配置proxyInterfaces属性。看到复数形式就能猜到是个数组或是集合。如果没有实现接口,也能处理。就要借助CGLIB类库直接操作.class文件。提到代理,肯定就要有被代理的对象,target属性配置被代理的对象。

注意:被代理的对象应该被IOC容器管理。

interceptorNames属性用于配置代理类。复数形式同样表示是数组或集合,并且对象也被IOC容器管理。

注意:如果没有实现接口,想借助CGLIB类库操作。那么需要配置proxyTargetClass属性并且属性value=”true”.

代码如下:

applicationContext.xml配置如下:

<!-- 使用JDK自带的动态代理,被代理的类必须要实现一个接口 -->
	<bean id="loginInterceptor" class="com.xt.right.spring.LoginInterceptor"></bean>
	<bean id="loginTarget" class="com.xt.right.LoginManagermentImpl"></bean>
	<bean id="login" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="proxyInterfaces">
			<value>com.xt.right.ILoginManager</value>
		</property>
		<property name="interceptorNames">
			<list>
				<value>loginInterceptor</value>
			</list>
		</property>
		<property name="target">
			<ref bean="loginTarget" />
		</property>
	</bean>

<!-- 使用CGLIB实现动态代理,被代理的类不需要实现接口。直接操作.class文件 -->
	<bean id="loginTarget2" class="com.xt.right.LoginManager2"></bean>
	<bean id="loginInterceptor2" class="com.xt.right.spring.CGLIBLoginInterceptor"></bean>
	<bean id="login2" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="proxyTargetClass" value="true">
		</property>
		<property name="target">
			<ref bean="loginTarget2" />
		</property>
		<property name="interceptorNames">
			<list>
				<value>loginInterceptor2</value>
			</list>
		</property>
	</bean>

 代理类:实现了MethodInterceptor接口中的invoke方法.arg0.getArguments()得到所有的参数。

 

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class CGLIBLoginInterceptor implements MethodInterceptor {

	public Object invoke(MethodInvocation arg0) throws Throwable {
		String name = (String)arg0.getArguments()[0]; 

	    if (name.equals("flash")) { 

	    	System.out.println("这才是真正的用户! "); 

	    	return arg0.proceed(); 

	    } else { 

	    	System.out.println("非法的用户~~~ "); 
	    return null; 

	    }
	}


}

 

被代理类:

public class LoginManager2 {
	public void login(String name) {
		System.out.println("欢迎 " + name + "登陆!"); 

	}
}