Spring AOP創建BeforeAdvice和AfterAdvice實例


 BeforeAdvice

  1、會在目標對象的方法執行之前被調用。

   2、通過實現MethodBeforeAdvice接口來實現。

   3、該接口中定義了一個方法即before方法,before方法會在目標對象target之前執行。

 

AfterAdvice

     1、在目標對象的方法執行之后被調用

     2、通過實現AfterReturningAdvice接口實現

 

實現目標:

        在方法之前調用執行某個動作。

 

IHello 和Hello:

public interface IHello {
   public void sayHello(String str);
}
public class Hello implements IHello {
    @Override
    public void sayHello(String str) {
    	System.out.println("你好"+str);
    }
}

SayBeforeAdvice:

public class SayBeforeAdvice implements MethodBeforeAdvice {

	@Override
	public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
		// TODO Auto-generated method stub
       System.out.println("在方法執行前做事情!");
	}

}

SayAfterAdvice文件:

public class SayAfterAdvice implements AfterReturningAdvice {

	@Override
	public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
		// TODO Auto-generated method stub
	    System.out.println("在方法執行后做事情!");
	}

}

  

 

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!-- 建立目標對象實例 -->
	<bean id="bean_hello" class="com.pb.Hello" />
	<!-- 創建執行前advice實例 -->
	<bean id="sba" class="com.pb.SayBeforeAdvice" />
	<!-- 創建執行后advice實例 -->
	<bean id="sfa" class="com.pb.SayAfterAdvice" />
	<!-- 建立代理對象 -->
	<bean id="helloProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
	    <!-- 設置代理的接口 -->
	    <property name="proxyInterfaces">
			<value>com.pb.IHello</value>
		</property>
		<!-- 設置目標對象實例 -->
		<property name="target">
			<ref bean="bean_hello"/>
		</property>
		<!-- 設置Advice實例 -->
		<property name="interceptorNames">
			<list>
			 	<value>sba</value>
			 	<value>sfa</value>
			</list>
		</property>
	</bean>
</beans>

  

Main執行:

public static void main(String[] args) {
		// TODO Auto-generated method stub
	    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
	    
	    IHello hello=(IHello)context.getBean("helloProxy");
	    hello.sayHello("訪客");
	}

  

執行效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM