码迷,mamicode.com
首页 > 数据库 > 详细

AOP的MethodBeforeAdvice

时间:2015-03-30 20:41:29      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

使用Spring自动生成代理类,spring利用的是动态代理机制 
接口 

Java代码 
public interface UserDao { 
void addUser(); 
void deleteUser(); 

两个实现: 

Java代码 
public class UserDaoMySqlImpl implements UserDao {   
  
@Override  
public void addUser() {   
  System.out.println("UserDaoMySqlImpl.addUser()");   
}   
  
@Override  
public void deleteUser() {   
  System.out.println("UserDaoMySqlImpl.deleteUser()");   
  
}   
  
}   



public class UserDaoOracleImpl implements UserDao { 

@Override 
public void addUser() { 
  System.out.println("UserDaoOracleImpl.addUser()"); 


@Override 
public void deleteUser() { 
  System.out.println("UserDaoOracleImpl.deleteUser()"); 



Device 
import java.lang.reflect.Method; 

import org.springframework.aop.MethodBeforeAdvice; 

public class UserDaoBeforeAdvice implements MethodBeforeAdvice { 

@Override 
public void before(Method arg0, Object[] arg1, Object arg2) 
   throws Throwable { 
  System.out.println("UserDaoBeforeAdvice.before()"); 




spring的配置文件 

Xml代码 
<!-- 配置实现类的bean,可以把所有的实现类都写上 -->  
<bean id="userdao" class="com.dowebber.spring.aop.UserDaoMySqlImpl"></bean>  
<!--配置Advice的bean -->  
<bean id="beforeadvice" class="com.dowebber.spring.aop.UserDaoBeforeAdvice"></bean>  
<!--配置spring自动生成代理对象所需要的一些参数 -->  
<bean id="userdaoproxy" class="org.springframework.aop.framework.ProxyFactoryBean">  
<property name="proxyInterfaces" value="com.dowebber.spring.aop.UserDao"/>  
<property name="target">  
  <ref bean="userdao"/>  
</property>  
<property name="interceptorNames">  
  <list>  
   <value>beforeadvice</value>  
  </list>  
</property>  
</bean>  


测试类: 

Java代码 
import org.springframework.context.ApplicationContext;   
import org.springframework.context.support.ClassPathXmlApplicationContext;   
  
public class TestUserDaoBeforeDevice {   
  
public static void main(String[] args) {   
     
  ApplicationContext context = new ClassPathXmlApplicationContext("com/dowebber/spring/aop/spring.xml");   
  UserDao dao = (UserDao)context.getBean("userdaoproxy");   
  dao.addUser();   
}   
  

AOP的MethodBeforeAdvice

标签:

原文地址:http://www.cnblogs.com/toSeeMyDream/p/4378970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!