当前位置: 移动技术网 > IT编程>开发语言>Java > 一篇教你看懂spring bean工厂和aop

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

2018年12月19日  | 移动技术网IT编程  | 我要评论

这篇文章为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就可以帮助自己快速掌握和回顾,与诸君共勉.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网