一篇教你看懂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就可以幫助自己快速掌握和回顧,與諸君共勉.


免責聲明!

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



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