Spring两大核心

IoC

控制:控制对象的创建及销毁(生命周期)
反转:将对象的控制权交给IoC容器

(一)为什么要使用IoC?
假设小明有一辆奥迪车,奥迪这个类里面定义了start()、turnLeft()、turnRight()、stop()这几个方法。然后小明回家的话肯定要有一个方法goHome()然后先创建一个对象,去调用这些方法。同时小明不可能只用车回家,比如还要买菜、旅游等等的活动都需要去用车。
那么问题来了,要是小明换了一辆奔驰车的话,这些在方法里面new的对象都需要重改。这里有一个方法就是把创建一辆车提出来,变成一个全局的对象,并且由于可能会再购进新的车,于是我们创建一个接口Car,让新的车去实现这个接口。
此时又有个问题,车真的需要由小明去创建(创造出来么)?答案肯定是否认的,小明只需要有一辆车去使用。此时我们自然就想到创建一个构造方法,把Car传进来。

(二)实现一个自己的IoC

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 1、实例化Bean
 * 2、保存Bean
 * 3、提供Bean
 */
public class IoCContainer {
    private Map<String,Object> beans = new ConcurrentHashMap<String, Object>();

    /**
     * 通过beanId获取一个Bean
     * @param beanId
     * @return 返回一个Bean
     */
    public Object getBean(String beanId){
        return beans.get(beanId);
    }

    /**
     * 委托容器创建一个Bean
     * @param clazz 要创建的Bean的class
     * @param beanId
     * @param paramBeanIds 要创建Bean的class的构造方法所需要的参数的BeanIds
     */
    public void setBean(Class<?> clazz,String beanId,String... paramBeanIds){
        //1、构造方法创建一个Bean,组装构造方法所许哟啊的参数值
        Object[] paramValues = new Object[paramBeanIds.length];
        for (int i = 0; i <paramBeanIds.length ; i++) {
            paramValues[i] = beans.get(paramBeanIds[i]);
        }

        //2、调用构造方法实例化Beans
        Object bean=null;
        for (Constructor<?> constructor : clazz.getConstructors()) {
            try {
                bean = constructor.newInstance(paramValues);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        if(bean==null){
//            throw  new RuntimeException("找不到合适的构造方法去实例化Bean");
//        }
        //3、实例化好的Bean放入beans里面
        beans.put(beanId,bean);
    }

}

(三)IoC的使用
新建一个Mevan工程,配置一下环境,这里有个坑就是Mevan里的jar包都是通过网络直接链接配置的,如果你的网络不好的话可能会一直找不到这个包。(我俺就是搞了一早上,活生生心态爆炸的例子)
在这里插入图片描述
配置IoC容器

<?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-3.2.xsd">

    <!-- name中的user可以取别名    scope="prototype" 或singleton="false"可以设置为非单例模式 -->

    <bean id="student" class="com.lzy.entity.e.Student">
        <property name="name" value="漳卅"></property>
        <property name="id" value="1"></property>
        <property name="address" ref="address"></property>
    </bean>

    <!-- 将address注入导student里面,用到了依赖注入(DL)-->
    <bean id="address" class="com.lzy.entity.e.Address">
        <property name="id" value="1"></property>
        <property name="name" value="汉江"></property>
    </bean>
</beans>

IoC容器的使用

public class Test {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student);
    }
}

(四)配置文件
1、bean标签完成对象的管理

id:对象名
class:对象模板类(所有交给IoC容器来管理的类必须有无参构造函数,因为Spring底层是通过反射机制来创建对象,调用的是无参构造)

2、对象的成员变量通过property标签完成赋值。

name:成员变量名
value:成员变量值(String)
ref:将IoC中的另外一个bean(Dl)

(五)IoC的底层原理

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ClassPathXmlApplicationContext implements ApplicationContext {
    private Map<String,Object> ioc = new HashMap();
    public Object get(String id) {
        return ioc.get(id);
    }

    public ClassPathXmlApplicationContext(String path)  {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read("./src/main/resources/"+path);
            Element root = document.getRootElement();
            Iterator<Element> iterator = root.elementIterator();
            while(iterator.hasNext()){
                Element element = iterator.next();
                String id=element.attributeValue("id");
                String classname=element.attributeValue("class");
                //反射机制创建对象
                Class clazz = Class.forName(classname);
                //获取无参构造器
                Constructor constructor = clazz.getConstructor();
                Object object = constructor.newInstance();
                //给每个对象赋值
                Iterator<Element> beanIter = element.elementIterator();
                while(beanIter.hasNext()){
                    Element property = beanIter.next();
                    String name = property.attributeValue("name");
                    String valStr = property.attributeValue("value");
                    String ref = property.attributeValue("ref");
                    if(ref==null){
                        String methodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
                        Field field = clazz.getDeclaredField(name);
                        Method method = clazz.getDeclaredMethod(methodName,field.getType());
                        //根据成员变量的数据类型将value进行转换
                        Object value = null;
                        if(field.getType().getName() == "int"){
                            value=Integer.parseInt(valStr);
                        }
                        else if(field.getType().getName() == "java.lang.String"){
                            value = valStr;
                        }
                        else if(field.getType().getName() == "long"){
                            value = Long.parseLong(valStr);
                        }
                        method.invoke(object,value);
                    }
                ioc.put(id,object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

(六)使用IoC的其它方法

<!--通过有参构造器去使用-->
<bean id="student3" class="com.lzy.entity.e.Student">
        <constructor-arg name="name" value="小明"></constructor-arg>
        <constructor-arg name="id" value="1"></constructor-arg>
        <constructor-arg name="address" ref="address"></constructor-arg>
    </bean>

(七)给bean注入集合

<bean id="student" class="com.lzy.entity.e.Student">
        <property name="name" value="漳卅"></property>
        <property name="id" value="1"></property>
        <property name="addresses">
            <list>
                <ref bean="address"></ref>
                <ref bean="address2"></ref>
            </list>
        </property>
    </bean>
    <bean id="address" class="com.lzy.entity.e.Address">
        <property name="id" value="1"></property>
        <property name="name" value="汉江"></property>
    </bean>

    <bean id="address2" class="com.lzy.entity.e.Address">
        <property name="name" value="莆田"></property>
        <property name="id" value="2"></property>
    </bean>

(八)scope作用域
Spring管理的bean是根据scope来生成的,表示bean的作用域一共有4种,默认为单例模式。

singleton:单例,表示通过Spring容器来获取的bean时唯一的。
prototype:原型,表示通过Spring容器获取的bean是不同的
request:请求,表示再一次HTTP请求内有效
session:会话,表示再一个一会会话内有效

request和session只用于web项目。

(九)Spring的继承
Spring时对象层面的继承,子对象可以继承父对象的属性值。甚至不同的类也可以继承属性值,但是子类里的属性要含有所有的父类的所有属性。

<bean id="student" class="com.lzy.entity.e.Student">
        <property name="name" value="漳卅"></property>
        <property name="id" value="1"></property>
        <property name="addresses">
            <list>
                <ref bean="address"></ref>
                <ref bean="address2"></ref>
            </list>
        </property>
    </bean>

    <bean id="stu" class="com.lzy.entity.e.Student" parent="student"><

(十)Spring的依赖
两个有依赖关系的bean,被依赖的bean一定会先创建,然后再创建依赖的bean。若A依赖于B,则B需要先被创建,后A再创建。

  <bean id="student" class="com.lzy.entity.e.Student"></bean>
    <bean id="user" class="com.lzy.entity.e.User" depends-on="student"></bean>
    <!--user依赖于student所以即使user调用在student前面的画也需要先创建student-->

(十一)Spring的p命名空间

<?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-3.2.xsd">
    <bean id="student" class="com.lzy.entity.e.Student" depends-on="user"></bean>
    <bean id="user" class="com.lzy.entity.e.User" ></bean>
</beans>

AOP

AOP:Aspect Oriented Programming面向切面编程
AOP优点:

降低模块之间的耦合度
使系统更容易扩展
更好的代码复用
非业务代码更加集中,不分散,便于统一管理
业务代码更加简洁存粹,不参杂其他代码的影响
(一)如何使用?

创建Maven工程,pom.xml添加

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
</dependencies>
(二)解决实际问题

在下面的代码中,我们可以看出每个方法都存在类似的一块,AOP的思想就是将这部分提取出来,到达接耦合效果。

public class CalImpl implements Cal {
    public int add(int num1, int num2) {
        System.out.println("add方法的参数是["+num1+","+num2+"]");
        int result = num1+num2;
        System.out.println("结果是"+result);
        return result;
    }

    public int sub(int num1, int num2) {
        System.out.println("sub方法的参数是["+num1+","+num2+"]");
        int result = num1-num2;
        System.out.println("结果是"+result);
        return result;
    }

    public int mul(int num1, int num2) {
        System.out.println("mul方法的参数是["+num1+","+num2+"]");
        int result = num1*num2;
        System.out.println("结果是"+result);
        return result;
    }

    public int div(int num1, int num2) {
        System.out.println("div方法的参数是["+num1+","+num2+"]");
        int result = num1/num2;
        System.out.println("结果是"+result);
        return result;
    }
}

通过下面代码创建一个代理对象(含有委托类的所有接口),在里面写好日志对象,并使用委托对象自己去调用业务代码,实现解耦合。

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class MyInvocationHandler implements InvocationHandler {
    //接收委托对象
    private Object object = null;

    //放回代理对象
    public Object bind(Object object) {
        this.object = object;
        return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
    }



    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName()+"方法的参数是"+ Arrays.toString(args));
        Object result = method.invoke(this.object,args);
        System.out.println(method.getName()+"的结果是"+result);
        return null;
    }
}

使用代理后简化的代码

public class CalImpl implements Cal {
    public int add(int num1, int num2) {
        int result = num1+num2;
        return result;
    }

    public int sub(int num1, int num2) {
        int result = num1-num2;
        return result;
    }

    public int mul(int num1, int num2) {
        int result = num1*num2;
        return result;
    }

    public int div(int num1, int num2) {
        int result = num1/num2;
        return result;
    }
}

当代理对象调用add方法时,会进入到invoke方法中,先执行我们写的日志打印方法名和参数,接着通过This.object委托对象自己去调用自己的业务(add方法),然后在打印日志信息。

import com.lzy.utils.Cal;
import com.lzy.utils.MyInvocationHandler;
import com.lzy.utils.impl.CalImpl;

public class Test1 {
    public static void main(String[] args) {
        Cal cal = new CalImpl();
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
        Cal cal1 = (Cal) myInvocationHandler.bind(cal);
        cal1.add(1,1);
    }
}

以上使用代理模式的思想。

下面我们来看一下使用AOP进行自动化生成代理对象:
(1)配置文件

<?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:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--自动扫描-->
    <context:component-scan base-package="com.lzy"></context:component-scan>

    <!-- 使aspect注解生效,为目标类自动生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

(2)定义切入点和通知

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;

@Aspect
@Component
public class logerAspect {
    @Before("execution(public int com.lzy.utils.impl.CalImpl.*(..))")
    public  void  before(JoinPoint joinPoint){
        //获取方法名
        String name = joinPoint.getSignature().getName();

        //获取参数
        String args = Arrays.toString(joinPoint.getArgs());

    }


    @AfterReturning(value = "execution(public int com.lzy.utils.impl.CalImpl.*(..))",returning = "result")
    public void after(JoinPoint joinPoint,Object result){
        System.out.println("结果是"+result);
    }

    @AfterThrowing(value = "execution(public int com.lzy.utils.impl.CalImpl.*(..))",throwing = "e")
    public void afterTrowing(JoinPoint joinPoint,Object e){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"抛出异常"+e);
    }
}

Context:component-scancom.lzy包中的所有类进行扫描,如果该类同时添加了*@Component*,则将该类扫描到IoC容器中,即IoC管理它的对象。
注:加入@Component的类,如果没有在spring中配置bean,就会自动生成类名的bean,例如CalImpl就会产生一个calImpl的bean

aop:aspectj-autopropoxy让Spring框架结合切面类和目标类自动生成动态代理对象。

(3)实现

public class Text2 {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");

        //获取代理对象
        Cal proxy = (Cal) applicationContext.getBean("calImpl");
        proxy.add(1,1);
    }
}

切面:横切面关注点被模块化的抽象对象
通知:切面对象完成的工作
目标:被通知的对象、即被横切的对象
代理:切面、通知、目标混合之后的对象
连接点:通知要插入业务代码的具体位置
切点:AOP通过切点定位的连接点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值