Spring AOP實現方式三之自動掃描注入【附源碼】

註解AOP實現  這裏惟一不一樣的就是application 裏面

不須要配置每一個bean都須要配置了,直接自動掃描

註冊,主要知識點是怎麼經過配置文件獲得bean,

注意類前面的@註解。

源碼結構:

image

一、首先咱們新建一個接口,love 談戀愛接口。

package com.spring.aop;

/**
 * 談戀愛接口
 * 
 * @author Administrator
 *
 */
public interface Love
{

    /*
     * 談戀愛方法
     */
    void fallInLove();
    void test() throws Exception;

}

二、咱們寫一個Person類實現Love接口 類聲明前面加上了

@Component 不加這個咱們沒法經過載入xml配置文件找到。

package com.spring.aop;

import org.springframework.stereotype.Component;

/**
 * 人對象
 * 
 * @author luwenbin006@163.com
 *
 */
@Component
public class Person implements Love
{

    /*
     * 重寫談戀愛方法
     */
    @Override
    public void fallInLove()
    {
        System.out.println("談戀愛了...");
    }

    @Override
    public void test() throws Exception
    {
        // TODO Auto-generated method stub
        throw new Exception("我就說大家在一塊兒不會幸福的,你能拿我怎麼滴?");
    }

}

三、下面咱們來寫aop 註解通知類 和前面有點不一樣哦 @Aspect前面加上了@Service

【執行方法前 執行方法後 執行方法先後也稱爲環繞方法 方法執行過程當中拋出異常】

package com.spring.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;

/**
 * 註解方式 aop通知類
 * 
 * @author luwenbin006@163.com
 *
 */
@Service
@Aspect
public class LoveHelper
{

    @Pointcut("execution(* com.spring.aop.*..*(..))")
    private void loveMethod()
    {
    }// 定義一個切入點

    // 在調用方法以前執行 執行攔截包com.spring.aop.*下全部的方法
    @Before("execution(* com.spring.aop.*..*(..))")
    public void before(JoinPoint point) throws Throwable
    {
        System.out.println("before::method "
                + point.getTarget().getClass().getName() + "."
                + point.getSignature().getName());
        System.out.println("談戀愛以前必需要彼此瞭解!");
    }

    // 在調用方法先後執行
    @Around("execution(* com.spring.aop.*..*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable
    {
        System.out.println("around::method "
                + point.getTarget().getClass().getName() + "."
                + point.getSignature().getName());
        if (point.getArgs().length > 0)
        {

            return point.proceed(point.getArgs());

        }
        else
        {

            return point.proceed();
        }
    }

    // 在調用方法以後執行
    @After("execution(* com.spring.aop.*..*(..))")
    public void afterReturning(JoinPoint point) throws Throwable
    {
        System.out.println("method " + point.getTarget().getClass().getName()
                + "." + point.getSignature().getName());
        System.out.println("咱們已經談了5年了,最終仍是分手了!");
        // System.out.println("咱們已經談了5年了,最終步入告終婚的殿堂!");
    }

    // 當拋出異常時被調用
    @AfterThrowing(value = "execution(* com.spring.aop.*..*(..))", throwing = "ex")
    public void doThrowing(JoinPoint point, Throwable ex)
    {
        System.out.println("doThrowing::method "
                + point.getTarget().getClass().getName() + "."
                + point.getSignature().getName() + " throw exception");
        System.out.println(ex.getMessage());
    }

}

四、配置好application.xml   就配置好bean和aop通知類 加上一句啓用註解模式

配置和自動掃描配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">



    <!--組件掃描 -->
    <context:component-scan base-package="com.spring.aop" />
    <aop:aspectj-autoproxy />

    <!-- //定義掃描根路徑爲leot.test,不使用默認的掃描方式 <context:component-scan base-package="com.spring.aop" 
        use-default-filters="false"> // 掃描符合@Service @Repository的類 <context:include-filter 
        type="annotation" expression="org.springframework.stereotype.Service" /> 
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" 
        /> </context:component-scan> -->
</beans>

五、編寫咱們spring getBean 輔助工具類 兩種方式, 一種是實現 ApplicationContextAware

接口 一種是繼承ApplicationObjectSupport

一、實現ApplicationContextAware接口

package com.spring.aop.springUtil;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContextHelper implements ApplicationContextAware
{

    private ApplicationContext context;

    // 提供一個接口,獲取容器中的Bean實例,根據名稱獲取
    public Object getBean(String beanName)
    {
        return context.getBean(beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        this.context = context;

    }

}

二、繼承ApplicationObjectSupport類

package com.spring.aop.springUtil;

import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Service;

@Service
public class SpringContextHelper2 extends ApplicationObjectSupport
{

    // 提供一個接口,獲取容器中的Bean實例,根據名稱獲取
    public Object getBean(String beanName)
    {
        return getApplicationContext().getBean(beanName);
    }

}

六、咱們以前的測試類也仍是能夠運行的哦~~~

package com.spring.aop;

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

import com.spring.aop.Love;

public class LoveTest
{

    public static void main(String[] args)
    {
        ApplicationContext appCtx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        Love love = (Love) appCtx.getBean("person");
        love.fallInLove();
        try
        {
            // 測試異常捕獲
            love.test();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

七、或者寫上Junit測試類

package com.love.test;

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

import com.spring.aop.Love;
import com.spring.aop.springUtil.SpringContextHelper;
import com.spring.aop.springUtil.SpringContextHelper2;

import junit.framework.TestCase;

public class LoveAopTest extends TestCase
{

    private SpringContextHelper helper;
    private SpringContextHelper2 helper2;
    ApplicationContext context;

    protected void setUp()
    {
        /* 開始test前的準備操做:初始化,獲取數據鏈接... */
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        helper = (SpringContextHelper) context.getBean("springContextHelper");
        helper2 = (SpringContextHelper2) context
                .getBean("springContextHelper2");

    }

    protected void tearDown()
    {
        /* 完成test後的清理工做:關閉文件, 關閉數據鏈接... */

    }

    public void testCase2()
    {

        Love love = (Love) helper.getBean("person");
        love.fallInLove();
        try
        {
            // 測試異常捕獲
            love.test();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            assertTrue(true);
        }
    }

    public void testCase3()
    {

        Love love = (Love) helper2.getBean("person");
        love.fallInLove();
        try
        {
            // 測試異常捕獲
            love.test();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            assertTrue(true);
        }
    }

}

八、看控制檯輸出結果 調用了咱們定義的aop攔截方法~~~ ok了

image_thumb[6]

 

九、源碼下載地址:源碼下載css

相關文章
相關標籤/搜索