1. 程式人生 > >Spring aop 攔截器(即面向切面程式設計)

Spring aop 攔截器(即面向切面程式設計)

package com.saic.grape;

public interface UserService {
    public void printUser(String user);
}

package com.saic.grape;

public class UserServiceImp implements UserService{

    @Override
    public void printUser(String user) {
        // TODO Auto-generated method stub
         System.out.println("printUser user:" + user);// 顯示user  
    }

}

package com.saic.grape;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;


public class UserInterceptor implements MethodInterceptor{
// AOP方法攔截器

   

    @Override
    public Object invoke(MethodInvocation arg0) throws Throwable {
         try{
                if (arg0.getMethod().getName().equals("printUser"))
                // 攔截方法是否是UserService介面的printUser方法
                {
                    Object[] args = arg0.getArguments();// 被攔截的引數
                    System.out.println("user:" + args[0]);
                    arg0.getArguments()[0] = "hello!";// 修改被攔截的引數
                }
                System.out.println(arg0.getMethod().getName() + "---!");
                return arg0.proceed();// 執行UserService介面的printUser方法
            } catch (Exception e) {
                throw e;
            }
    }
}

package com.saic.grape;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class TestInterceptor{

    public static void main(String[] args){
        ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:aop.xml");
        //ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");    
        UserService us = (UserService) ctx.getBean("userService");
        us.printUser("ssss");

    }
}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <!-- 業務元件 -->
    <bean id="userServiceImp"  class="com.saic.grape.UserServiceImp" />
    <!-- AOP攔截器(面向切面程式設計) -->
    <bean id="userInterceptor" class="com.saic.grape.UserInterceptor" />

    <bean id="userService" class="org.springframework.aop.framework.ProxyFactoryBean">
      <!-- 代理介面 -->
        <property name="proxyInterfaces">
            <value>com.saic.grape.UserService</value>
        </property>
       <!-- 目標實現類 -->
        <property name="target">
            <ref local="userServiceImp" />
      </property>
        <!-- 攔截器 -->
        <property name="interceptorNames">
            <list>
                <value>userInterceptor</value>
            </list>
        </property>
    </bean>

</beans>