1. 程式人生 > >一篇教你看懂spring bean工廠和aop

一篇教你看懂spring bean工廠和aop

這篇文章為spring回顧總結的第二篇,本篇主要分為兩個部分,分別是spring的bean工廠的實現.spring的aop實現原理,這兩部分也是面試當中問的比較多的.

spring的bean工廠的實現

spring的bean工廠的實現可以有以下三種方式

  1. 靜態工廠實現
public class StaticCarFactory {
    public  static Map<String,Car> carMap = new HashMap<>();
    static {
        carMap.put("audi",new Car("audi","330000"));
        carMap.put("ford",new Car("ford","40000"));
    }

    public  static  Car getCar( String name){
        return  carMap.get(name);
    }
}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--通過靜態工廠方法配置bean,不是配置靜態工廠方法例項,而是bean的例項
    factory-method:指向靜態工廠方法的名稱
    constructor-arg:如果工廠方法需要傳入引數,使用constructor-arg配置傳入的引數
    -->
    <bean id="car1" class="com.springtest.beanFactory.StaticCarFactory"
          factory-method="getCar">
        <constructor-arg value="audi"/>
    </bean>


    <!--配置工廠例項-->
    <bean id="carFactory" class="com.springtest.beanFactory.InstanceCarFactory">
    </bean>
    <!-- 通過例項工廠方法來配置bean-->
    <bean id="car2" factory-bean="carFactory" factory-method="getCar">
        <constructor-arg value="ford"/>
    </bean>

</beans>
  1. 例項工廠實現
public class InstanceCarFactory {
    private Map<String, Car> cars = null;

    public InstanceCarFactory() {
        cars = new HashMap<String, Car>();
        cars.put("audi", new Car("audi", "300000"));
        cars.put("ford", new Car("ford", "600000"));

    }

    public Car getCar(String name) {
        return cars.get(name);
    }

}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--通過靜態工廠方法配置bean,不是配置靜態工廠方法例項,而是bean的例項
    factory-method:指向靜態工廠方法的名稱
    constructor-arg:如果工廠方法需要傳入引數,使用constructor-arg配置傳入的引數
    -->
    <bean id="car1" class="com.springtest.beanFactory.StaticCarFactory"
          factory-method="getCar">
        <constructor-arg value="audi"/>
    </bean>


    <!--配置工廠例項-->
    <bean id="carFactory" class="com.springtest.beanFactory.InstanceCarFactory">
    </bean>
    <!-- 通過例項工廠方法來配置bean-->
    <bean id="car2" factory-bean="carFactory" factory-method="getCar">
        <constructor-arg value="ford"/>
    </bean>

</beans>
  1. 實現spring提供的FactoryBean介面
/**
 * 自定義的factorybean需要實現spring提供的factorybean介面
 */
public class CarFactoryBean implements FactoryBean<Car> {
    private String brand;

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public Car getObject() throws Exception {
        return new Car("BMW","430000");
    }

    @Override
    public Class<?> getObjectType() {
        return Car.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

配置檔案

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

    <!--通過factorybean來配置bean的例項
        class:指向factorybean的全類名
        property:配置factorybean的屬性
        但是實際返回的是例項確實是factorybean的getobject()方法返回的例項
    -->
    <bean id="car1" class="com.springtest.factoryBean.CarFactoryBean">
        <property name="brand" value="BMW"></property>
    </bean>
</beans>

spring的aop的實現原理

學習aop,首先要了解兩點

  • 什麼是aop?
    在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面向切面程式設計,通過預編譯方式和執行期動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的一個重要內容,是函數語言程式設計的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。(摘自百度百科)

  • 為什麼要使用aop?
    使用aop主要為了解決兩個問題:
    1. 程式碼混亂.即非核心程式碼和核心程式碼混在一起,難以維護或者提高維護成本,
    2. 程式碼分散.一旦非核心程式碼需要更改或者替換部分邏輯,那麼全部方法中的相關的邏輯都要改動,相當麻煩;
    3. 幾個關鍵詞
      • Aspect(切面) 橫切關注點
      • Advice(通知) 切面必須要完成的工作
      • Target(目標) 被通知的物件
      • Proxy(代理) 向目標物件應用通知之後建立的物件
      • Joinpoint(連線點) 程式執行的 某個特定的位置,比如方法呼叫前,呼叫後,方法丟擲異常後等.是實際存在的物理位置.
      • pointcut(切點) 每個類都有多個連線點.aop通過切點定位到連線點.切點和連線點不是一對一的關係,一個切點可匹配多個連線點,切點通過org.springframework.aop.pointcut介面進行描述,使用類和方法作為連線點的查詢條件.
        類比記憶:連線點相當於資料庫中的記錄,切點相當於查詢條件.
        程式碼示例如下:
        首先定義介面:
        ```
        public interface Calculation {

    int add(int i, int j);

    int sub(int i, int j);
    }

    定義實現類

    public class CalculationImpl implements Calculation {
    @Override
    public int add(int i, int j) {
    //業務功能前加log記錄
    System.out.println("這個" + i + ";那個" + j);
    int result = i + j;
    System.out.println("結果是"+result);
    return result;
    }

    @Override
    public int sub(int i, int j) {
    System.out.println("這個" + i + ";那個" + j);
    int result = i - j;
    System.out.println("結果是"+result);
    return result;
    }
    }

    可以看到,模擬加了log日誌的話,就要在方法核心程式碼前後新增無關程式碼,並且所有用到log的地方都要新增,難以維護;
    下面上改進的程式碼:

    public class CalculationLoggingImpl implements Calculation {
    @Override
    public int add(int i, int j) {
    //業務功能前加log記錄
    int result = i + j;
    return result;
    }

    @Override
    public int sub(int i, int j) {
    int result = i - j;
    return result;
    }
    }

    這裡是一個代理類,
    public class CalculationLoggingProxy {
    /**
    • 要代理的物件
      */
      private Calculation target;

    public CalculationLoggingProxy(Calculation target){
    this.target = target;
    }
    public Calculation getLoggingProxy() {
    Calculation proxy = null;
    ClassLoader loader = target.getClass().getClassLoader();
    Class[] interfaces = new Class[]{Calculation.class};
    //當呼叫代理物件其中方法時,該執行的程式碼
    /**
    * proxy:正在返回的那個代理物件,
    * method:正在被呼叫的方法
    * args:呼叫方法時傳入的引數;

    /
    InvocationHandler handler = new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String name = method.getName();
    System.out.println("method:"+ name+"params:"+ Arrays.asList(args));
    Object invoke = method.invoke(target, args);
    System.out.println(invoke);
    return invoke;
    }
    };
    proxy = (Calculation) Proxy.newProxyInstance(loader, interfaces, handler);
    return proxy;
    }
    }

    Test類:

public class Test {
public static void main(String[] args) {

    //1,不使用代理

// Calculation calculation = new CalculationImpl();
// calculation.add(1,2);
// calculation.sub(3,1);
//2.使用代理
Calculation target = new CalculationLoggingImpl();
Calculation proxy = new CalculationLoggingProxy(target).getLoggingProxy();
proxy.add(1, 2);

}

}

   一個簡單的aop例子就可以跑起來了,可以看到,使用了動態代理之後,可以將無關核心業務的log程式碼抽取到代理類中去新增維護,並且無關被代理類究竟是哪一個,省去了很多重複和不必要的程式碼,提高了程式碼的靈活性和可維護性.

-  aop的實現框架
 aspectJ是java社群最完整,最流行的aop框架,在Spring2.0以上版本中,可以使用基於aspectJ註解或者基於xml配置的aop.
  那麼我們還是分兩步來看aspectJ實現aop的過程,先看基於註解實現的,再看基於xml配置實現的.
      1. 基於註解實現
首先把類交給ioc容器管理

@Component
public class CalculationLoggingImpl implements Calculation {
@Override
public int add(int i, int j) {
//業務功能前加log記錄
int result = i + j;
return result;
}

@Override
public int sub(int i, int j) {
    int result = i - j;
    return result;
}

}
```
宣告一個切面,在此需要注意,@Aspect在aspectjweaver 這個jar包裡面,使用idea生成spring專案時沒有出現,需要自己去下載加入.

/**
 * 該類宣告為一個切面,需要把該類放在aop容器當中,再宣告為一個切面
 */
@Aspect
@Component
public class LoggingAspect {

    /***
     * 宣告該方法為一個前置通知
     */
    @Before("execution(public int com.springtest.aop.CalculationLoggingImpl.add(int,int))")
    public void beforeMethod(JoinPoint point){
        //獲取當前方法名
        String methodName = point.getSignature().getName();
      //獲取當前方法的引數列表
        List<Object> args = Arrays.asList(point.getArgs());
        System.out.println("this is before logging...");
        System.out.println("this is method  "+methodName+"  params is " +args);
        System.out.println("this is before logging...");
    }

}

簡單配置檔案 如下:

<?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:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置自動掃描的包-->
    <context:component-scan base-package="com.springtest.aop"></context:component-scan>
    <!--使AspectJ註解起作用,自動為匹配的類生成代理物件-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

Test程式碼

         //3.使用日誌切面
        //3.1 建立springIOC容器
        ApplicationContext cxt = new  ClassPathXmlApplicationContext("applicationContext-aop.xml");
        //3.2 從IOC容器中獲取bean
        Calculation bean = cxt.getBean(Calculation.class);
        //3.3 使用bean
        System.out.println(bean.add(1,2));

實現結果:

this is before logging...
this is method  add  params is [1, 2]
this is before logging...
3

可以看到,已經使用loggingAspect切面將log日誌資訊加在了add方法執行之前.
將@before替換為@after,即變更為後置通知,無論是否出現異常,後置通知都會執行.
將@before替換為@AfterReturning,變更為方法結束後通知.在方法正常結束後執行.
@AfterThrowing丟擲異常後通知,在方法丟擲異常後執行,可以訪問到方法丟擲的異常.
@around 環繞通知,需要攜帶ProceddingJoinpoint型別的引數,類似於動態代理實現的過程.ProceddingJoinpoint型別的引數可以決定是否執行目標方法,環繞通知必須要有返回值,沒有返回值會報錯,如下程式碼:

    @Around("execution(public int com.springtest.aop.CalculationLoggingImpl.add(int,int))")
    public void aroundMethod(ProceedingJoinPoint point) {
        try {
            //獲取當前方法名
            String methodName = point.getSignature().getName();
            //獲取當前方法的引數列表
            List<Object> args = Arrays.asList(point.getArgs());
            System.out.println("this is around loggingbegin...");
            System.out.println("this is method  " + methodName + "  params is " + args);

            Object result = point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("this is around loggingend...");

    }

沒有返回值,控制檯列印如下:

this is around loggingbegin...
Exception in thread "main" org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract int com.springtest.aop.Calculation.add(int,int)
this is method  add  params is [1, 2]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:227)
this is around loggingend...
    at com.sun.proxy.$Proxy8.add(Unknown Source)
    at com.springtest.aop.Test.main(Test.java:24)

Process finished with exit code 1

表明沒有返回值,加上返回值之後,不再報錯.
另外需要注意的幾點:
1.當有多個切面同時使用時,可以使用@order標籤來指定優先順序;
2. 切面表示式是可以重用的,定義一個方法,用於宣告切面表示式,一般該方法內部不需要再寫任何實現程式碼,使用@Pointcut來宣告切入點表示式.格式如下:

 /**
     * 定義一個方法,用於宣告切入點表示式,不需要在方法內部再加入其它程式碼
     */
    @Pointcut("execution(public int com.springtest.aop.Calculation.*(int, int))")
    public void declarePointCutExpressionEP(){}

    @Around(value ="declarePointCutExpressionEP()")
    public Object aroundMethod(ProceedingJoinPoint point) {...}

注意:這裡可能會報錯:error at ::0 can't find referenced pointcut declarePointCutExpressionEP,經查證,是因為Aspectweaver這個jar包版本的問題,我使用jdk1.8,最初 使用aspectjweaver-1.6.2.jar,報這個錯誤,更換為aspectjweaver-1.9.2.jar之後,錯誤消失.
總結一下,這篇文章詳細介紹了spring框架的bean工廠的實現以及aop的簡單實現和AspectJ框架的運用.想要熟練運用spring,在面試中不是簡單的背記敘述aop的原理,這些基本的東西是要過一遍的,並且掌握它的原理.
俗話說"好記性不如爛筆頭",在IT行業裡,不能只是一味去看視訊,看書,而是要在聽說看的同時,多寫程式碼.有的時候,比較難理解的原理,其實寫一個簡單的helloworld的demo就可以幫助自己快速掌握和回顧,與諸君共勉.