代理分JDK動(dòng)態(tài)代理(代理接口)和CGLIB代理(代理具體類),CGLIB代理是目標(biāo)對(duì)象的子類
aop代理就是由aop框架動(dòng)態(tài)生成的一個(gè)對(duì)象,spring的aop代理大都由ProxyFactoryBean工廠類產(chǎn)生,配置ProxyFactoryBean需要如下兩個(gè)屬性:1.代理的目標(biāo)對(duì)象 2.處理(Advice)
一、代理接口
實(shí)例:基于AOP的權(quán)限認(rèn)證
1.Service組件接口
public interface TestService
{
void view();
void modify();
}
2.Service接口實(shí)現(xiàn)類
public class TestServiceImpl implements TestService
{
public void view()
{
System.out.println("查看數(shù)據(jù)");
}
public void modify()
{
System.out.println("修改數(shù)據(jù)");
}
}
3.攔截器類
public class AuthorityInterceptor implements MethodInterceptor
{
private User user;
public void setUser(User user)
{
this.user=user;
}
//必需實(shí)現(xiàn)的方法
public Object invoke(MethodInvocation invocation) throws Throwable
{
String methodName=invocation.getMethod().getName();
if(!user.equals("admin) && !user.equals("registedUser"))
{
System.out.println("您無權(quán)查看");
return null;
}
else if(user.equals("registedUser") && methodName.equals("modify))
{
System.out.println("您不是管理員,無權(quán)修改");
return null;
}
else
{
return invocation.proceed();
}
}
4.spring 配置文件
//
1.配置目標(biāo)bean
<bean id="serviceTarget" class="com.lhb.TestServiceImpl"/>
//2.配置攔截器
<bean id="authorityInterceptor" class="com.lhb.AuthorityInterceptor">
<property name="user" value="admin"/>
</bean>
//3.配置代理工廠Bean,產(chǎn)生aop代理
<bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
//4.指定aop代理所實(shí)現(xiàn)的接口
<property name="proxyInterfaces" value="com.lin.TestService"/>
//5.指定aop代理所代理的目標(biāo)bean
<property name="target" ref="serviceTarget"/>
//6.指定aop代理所需要的攔截器列表
<property name="interceptorNames">
<list>
<value>authorityInterceptor</value>
</list>
</property>
</bean>
以上配置中目標(biāo)bean被暴露在容器中,可以被 客房端代碼直接訪問,所以將目標(biāo)bean定義成代理工廠的嵌套bean:
配置攔截器
<bean id="authorityInterceptor" class="com.lhb.AuthorityInterceptor">
<property name="user" value="admin"/>
</bean>
.配置攔截器
<bean id="authorityInterceptor" class="com.lhb.AuthorityInterceptor">
<property name="user" value="admin"/>
</bean>
配置代理工廠Bean,產(chǎn)生aop代理
<bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
//4.指定aop代理所實(shí)現(xiàn)的接口
<property name="proxyInterfaces" value="com.lin.TestService"/>
//5.指定aop代理所代理的目標(biāo)bean
<property name="target">
//以嵌套bean的形式定義目標(biāo)bean,避免客戶端直接訪問目標(biāo)bean
<bean class="com.lin.TestServiceImpl">
</proterty>
//6.指定aop代理所需要的攔截器列表
<property name="interceptorNames">
<list>
<value>authorityInterceptor</value>
</list>
</property>
</bean>
posted on 2008-05-17 22:53
長(zhǎng)春語林科技 閱讀(2295)
評(píng)論(0) 編輯 收藏 所屬分類:
spring