Spring的一些基本笔记

Spring笔记概要

1.程序的耦合

1.1 概念

*      耦合:程序间的依赖关系
*          包括:
*              类之间的依赖
*              方法之间的依赖
*      解耦:降低程序见得依赖关系
*      实际开发中: 应该做到:编译期不依赖,运行时才依赖
*      解耦的思路:
*          第一步:使用反射来创建对象,而避免使用关键字new
*          第二部:通过读取配置文件啦获取要出案件的对象的全限制类名

2.IoC容器

2.1 获取IoC核心容器,并且根据id获取对象

注解解释
    /**
     *  获取spring的IOC核心容器,并更具id获取对象
     *
     *  ApplicationContext的三个常用实现类
     *      ClassPathXmlApplicationContext:他可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了
     *      FileSystemXmlApplicationContext:他可以加载磁盘任意路径下的配置文件(必须有访问权限)
     *      AnnotationConfigApplicationContext:读取注解创建容器
     *
     * 核心容器的两个接口引发出的问题
     * ApplicationContext:          单例对象使用
     *       他在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取玩配置文件马上就穿件配置文件中的配置对象。
     * BeanFactory:                 多例对象使用
     *       他在构建核心容器时,创建对象采取的策略是延迟加载的方式,也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象
     */
java代码
    public static void main(String[] args) {
       //1.获取核心容器对象
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new FileSystemXmlApplicationContext("D:\\PROGRAM2\\SSM\\Spring\\Spring_day01_spring03\\src\\main\\resources\\bean.xml");
        //2.根据id获取Bean对象
        AccountService as = (AccountService) ac.getBean("accountService");//两种方法都可以,第一个是给一个bean然后强转
        AccountDao adao = ac.getBean("accountDao",AccountDao.class);//第二个是给一个bean和字节码文件class

        System.out.println(as);
        System.out.println(adao);
//       as.saveAccount();
        }
xml文件
<!--    把对象的创建交给spring管理-->
<bean id="accountService" class="com.ljh.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.ljh.dao.impl.AccountDaoImpl"></bean>
  • AccountDao ac = new AccountDaoImpl
  • new的是实现了,所以注入的就是实现类对象

2.2 spring中bean的细节(三种创建Bean对象的方式)

创建Bean的三种方式
<!--    创建bean的三种方式-->
<!--        第一种方式,使用默认构造函数创建
                在spring的配置文件中使用bean标签,配以id和class属性之后,并没有其他属性和标签时
                采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建-->

    <bean id="accountService" class="com.ljh.service.impl.AccountServiceImpl"></bean>

<!--            第二种方式 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
        例:我们现在有一个对象,他是一个工厂叫InstanceFactory。里面有个方法可以创建service对象
        需要定义一个service对象 是由factory-bean里面的id所指向的工厂中的 factory-method方法来获取的-->
    <bean id="InstanceFactory" class="com.ljh.factory.InstanceFactory"></bean>
    <bean id="AccountService" factory-bean="InstanceFactory" factory-method="getAccountService"></bean>


<!--    第三种方法,使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)-->
    <bean id="AccountService" class="com.ljh.factory.StaticFactory" factory-method="getAccountService"></bean>
Bean的作用范围
<!--    bean的作用范围
        bean标签的scope属性:
            作用:用于指定bean的作用范围
            取值:常用是单例和多例
                singleton:单例的(默认值)
                prototype:多例的
                request:作用于web应用的请求范围
                session:作用于web应用的会话范围
                global-session:作用于集群环境的会话范围(全局会话范围),但不是集群环境时,他就是session-->
    <bean id="accountService" class="com.ljh.service.impl.AccountServiceImpl" scope="singleton"></bean>
Bean的生命周期
<!--    bean的生命周期
            单例对象:立即创建
                出生:当容器创建时对象出生
                活着:只要容器还在,对象一直活着
                死亡:容器销毁,对象消亡
                总结:和容器一致
            多例对象:延迟创建
                出生:当使用对象时spring框架为我们创建
                活着:对象在使用过程中一直活着
                死亡:当对象长时间不用,且没有别的对象引用时,由java的垃圾回收器回收
                -->

2.3 Spring的DI(依赖注入)

  • DI =>Dependency Injection

  • ioc的依赖管理

  • <!--IOC作用:
                    降低程序间的耦合(依赖关系)
                依赖关系的管理:
                    以后都交给了spring来维护
                在当前类中需要用到其他类的对象,由spring为我们提供,我们只需要在配置文件中说明
                依赖关系的维护:就称之为依赖注入。-->
    
依赖注入的数据
能注入的数据:有三类
    基本类型和String
    其他的bean类型(在配置文件中或者注解配置过的bean)
    复杂类型(集合类型)
注入方式:有三种
     第一种:使用构造函数提供
     第二种:使用set方法提供
     第二种:使用注解提供
  • 2.3.1 使用构造函数提供

  • <!--    使用构造函数注入:一般不用
             使用的标签:constructor-arg
             标签出现的位置:bean标签的内部
             标签中的属性:
             type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
             index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置从0开始
             name:用于指定给构造函数中指定名称的参数赋值
             ==========以上三个用于指定给构造函数中哪个参数赋值=================
             value:用于给基本类型和String类型的数据
             ref:用于指定其他的bean类型数据、他指的就是在Spring的IOC核心容器中出现过的bean对象
    
             特点:
                在获取bean对象时,注入数据时必须的操作,否则操作无法创建成功
             弊端:
                改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供
             -->
            <bean id="accountService" class="com.ljh.service.impl.AccountServiceImpl">
                <constructor-arg name="name" value="ljh"></constructor-arg>
                <constructor-arg name="age" value="18"></constructor-arg>
                <constructor-arg name="birthday" ref="now"></constructor-arg>
            </bean>
    
    <!--    配置一个日期对象-->
        <bean id="now" class="java.util.Date"></bean>
    
  • 2.3.2 使用set方法

  • <!--    set方法注入:常用
            涉及标签:property
            出现的位置:bean标签的内部
                name:用于指定注入是所调用的set方法名称
                 value:用于给基本类型和String类型的数据
                 ref:用于指定其他的bean类型数据、他指的就是在Spring的IOC核心容器中出现过的bean对象
    
            set方法优势:
                    创建对象时没有明确的限制,可以直接使用默认的构造函数
                弊端:
                    如果某个成员必须有值,则获取对象时有可能set方法没有执行-->
        <bean id="accountService2" class="com.ljh.service.impl.AccountServiceImpl2">
            <property name="name" value="ljh"></property>
            <property name="age" value="20"></property>
            <property name="birthday" ref="now"></property>
        </bean>
    
  • 2.3.3 给复杂数据类型注入数据

  • <!--    复杂类型的注入
                用于给List结构集合注入的标签
                    list,array,set
                用于给Map,properties注入的标签
                    map,props-->
        <bean id="accountService3" class="com.ljh.service.impl.AccountServiceImpl3">
            <property name="myStrs">
                <array>
                    <value>AAA</value>
                    <value>BBB</value>
                    <value>CCC</value>
                </array>
            </property>
    
            <property name="myList">
                <list>
                    <value>AAA</value>
                    <value>BBB</value>
                    <value>CCC</value>
                </list>
            </property>
    
            <property name="mySet">
                <set>
                    <value>AAA</value>
                    <value>BBB</value>
                    <value>CCC</value>
                </set>
            </property>
    
            <property name="myMap">
                <map>
                    <entry key="TestA" value="AAA"></entry>
                    <entry key="TestB">
                        <value>BBB</value>
                    </entry>
                </map>
            </property>
    
            <property name="myProps">
                <props>
                    <prop key="testC">ccc</prop>
                    <prop key="testD">ddd</prop>
                </props>
            </property>
        </bean>
    

3 IoC核心容器的注解注入

3.1 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"
       xmlns:context="http://www.springframework.org/schema/context"
       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">
    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中
    ,而是一个名称为context名称空间和约束中-->
    <context:component-scan base-package="com.ljh"></context:component-scan>
</beans>

3.2 用于创建对象使用的注解

<!-- * 用于创建对象的
 *      他们的作用就和在XML配置文件中编写一个<bean></bean>实现的功能是一样的
 *      @Component:
 *          作用:用于把当前的对象存在spring中
 *          属性:
 *              value:用于指定bean的id,当我们不写时,他的默认值是当前类名,且首字母小写
 *      @Controller:一般用于表现层
 *      @Service:一般用于业务层
 *      @Repository:一般用在持久层
 *      以上三个注解他们的作用和属性与Component是一模一样的
 *      他们三个是spring框架为我们提供明确三层使用的注解,是我们在三层对象更加清晰(就和html的head,div,foot一样)-->

3.3 用于注入数据的注解

/*
 * 用于注入数据的
 *      他们的作用就和在XML配置文件中的<bean> <property> </property> </bean> (bean标签中的property)的作用是一样的
 *      @Autowired:
 *          作用:自动按照类型注入。只要容器中有为唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *               如果ioc容器中没有任何bean类型和要注入的变量类型匹配,则报错
 *               如果ioc容器中有多个类型匹配时:
 *          出现的位置:
 *              可以是变量上,可以是方法上
 *      @Qualifier
 *          作用: 按照类中注入的基础之上在按照名称注入。他在给类成员注入时不能单独使用,但是在给方法参数注入是可以
 *          属性:
 *              value:用于指定注入bead的id
 *      @Resource
 *          作用:直接按照bean的id注入,他可以独立使用
 *          属性:
 *              name:用于指定bean的id
 *       以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
 *       另外,集合类型的注入只能通过xml来实现
 *
 *      @Value
 *          作用:用于注入基本类型和String类型的数据
 *          属性:
 *              value:用于指定数据的值,他可以使用spring中spEL(spring的EL表达式)
 *                      SpEL的写法:${表达式}*/
  • 在使用注解注入时候需要注意,AutoWired不一定可以注入,可以搭配选择Qualifier或者直接使用Resource

3.4 用于改变作用范围和生命周期相关的注解

/*
 * 用于改变作用范围的
 *      他们的作用就和在XML配置文件中<bean scope=“”></bean>的作用是一样的
 *      @Scope:
 *          作用:用于指定bean的作用范围
 *          属性:
 *              value:指定范围的取值:常用取值:singleton prototype 单例和多例 默认是单例
 *
 * 和生命周期相关的
 *      他们的作用就和XML配置文件中的<bean init-method="" destroy-method=""></bean>的作用是一样的
 *      PerDestroy:用于指定销毁方法
 *      PostConstruct:用于指定初始化方法*/

4.取消xml的注解


/**
 * 该类是一个配置类,他的作用和bean.xml的作用一样
 * Spring中的新注解
 * @Configuration
 *      作用:指定当前类是一个配置类
 *      细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
 *              ApplicationContext ac = new AnnotationConfigApplicationContext(springConfiguration.class);
 * @ComponentScan
 *      作用:用于中国注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:他和basePackages的作用是一样的。都是用于指定创建容器时要扫描的包
 *                  我们使用了这个注解就等同于在xml中配置了
 *                  <context:component-scan base-package="com.ljh"></context:component-scan>
 *
 * @Bean
 *      作用:用于把当前方法得返回值作为bean对象存入spring的ioc容器中
 *      属性:
 *          name:用于指定bean的id、当不写时,默认值是当前方法的名称
 *      细节:
 *          当我们使用直接配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
 *          查找的方式和Autowired注解的作用是一样的,如果有类型唯一匹配的类就注入,没有匹配就报错,如果有多个匹配和Autowired一样
 * @Import:
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码
 *                  当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
 * @PropertySource:
 *      作用:用于指定properties文件的位置
 *      属性:
 *          value:文件的名称和文件的路径
 *                  关键字:classpath,表示类路径下
 */
@Configuration
@ComponentScan(basePackages = {"com.ljh"})//basePackages属性和value属性都可以,两个一样。里面为数组,为多个时要用{}
@Import(JdbcConfig.class)
@PropertySource("classpath:JdbcConfig.properties")
public class springConfiguration {

}


/**
 * 和spring链接数据库相关的配置类
 */
@Configuration //这个时候不能省略。
// ApplicationContext ac = new AnnotationConfigApplicationContext(springConfiguration.class,jdbcConfig.class);
// 这样也就可以不用写注解了
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    /**
     * 用于创建一个QueryRunner对象,但是这个和xml中配置数据库源配置还有区别
     *  就是xml中是可以 把对象存到spring的核心容器中,而没有注解的方法就没有这个功能。我们给他加上这个注解就可以实现两个一致
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")     //多例
    public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "ds2")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "ds1")
    public DataSource createDataSource1(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql:///ljh02");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }
}

5.动态代理

  • 由于每个的数据库操作是一个多例对象,每个之后都会有新对象产生,所以不能使用事务的回滚,直接采用动态代理(后续使用Spring的AOP操作使用)

  •     动态代理
               特点:字节码随用随创建,随用随加载
               作用:不修改源码的基础上对方法增强
    

5.1 基于接口的动态代理

/**
 * 模拟一个用户
 */
public class Client {
    public static void main(String[] args) {
        final Producer producer = new Producer();

        /**
         * 动态代理
         *      特点:字节码随用随创建,随用随加载
         *      作用:不修改源码的基础上对方法增强
         *      分类:
         *          基于接口的动态代理
         *          基于子类的动态代理
         *      基于接口的动态代理:
         *          涉及的类:Proxy
         *          提供者:JDK
         *      如何创建代理对象:
         *          使用Proxy类中的newProxyInstance方法
         *      创建代理对象的要求:
         *          被代理类最少实现一个接口,如果没有则不能使用
         *      newProxyInstance方法的参数:
         *          ClassLoader:类加载器
         *                  他是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。代理谁写谁的类加载器,固定写法
         *          Class[]:字节码数组:
         *                  他适用于让代理对象的被代理对象有相同的方法,固定写法
         *          InvocationHandler:用于提供增加的代码
         *                  让我们写如何代理,我们一般都是写一个改接口的实现类,通常情况下就是写一个匿名内部类,但不是必须的
         *                  此接口的实现类都是谁用谁写
         *
         */
        IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 作用:执行被代理对象的任何接口方法都会经过该方法
                     * 方法参数的含义
                     *      @param proxy 代理对象的引用
                     *      @param method   当前执行的方法
                     *      @param args     当前执行方法所需的参数
                     *      @return      和被代理对象有相同的返回值
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //提供增强的代码:
                        Object returnValue = null;
                        //1.获取方法执行的参数
                        Float money = (Float) args[0];
                        //2.判断当前方法是不是销售
                        if("saleProduct".equals(method.getName())){
                            returnValue = method.invoke(producer, money*0.8f);
                        }
                        return returnValue;
                    }
                });
        proxyProducer.saleProduct(1000f);
    }
}

5.2 基于子类的动态代理


/**
 * 模拟一个用户
 */
public class Client {
    public static void main(String[] args) {
        final Producer producer = new Producer();

        /**
         * 动态代理
         *      特点:字节码随用随创建,随用随加载
         *      作用:不修改源码的基础上对方法增强
         *      分类:
         *          基于接口的动态代理
         *          基于子类的动态代理
         *      基于子类的动态代理:
         *          涉及的类:Enhancer
         *          提供者:第三方cglib库
         *      如何创建代理对象:
         *          使用Enhancer类中的create方法
         *      创建代理对象的要求:
         *          被代理类不能是最终类
         *      create方法的参数:
         *          Class:字节码:
         *                  它适用于指定被代理对象的字节码
         *          Callback:用于提供增加的代码
         *                  让我们写如何代理,我们一般都是写一个改接口的实现类,通常情况下就是写一个匿名内部类,但不是必须的
         *                  此接口的实现类都是谁用谁写
         *                  我们一般写的都是该接口的子接口实现类:MethodInterceptor
         *
         */
        Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             * 执行被代理对象的任何方法都会经过此方法
             * @param proxy
             * @param method
             * @param args
             *      以上三个参数和基于接口的动态代理中invoke方法的参数是一样的
             * @param methodProxy 当前执行方法得代理对象
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //提供增强的代码
                Object returnValue = null;
                //1.获取方法执行的参数
                Float money = (Float) args[0];
                //2.判断当前方法是不是销售
                if("saleProduct".equals(method.getName())){
                    returnValue = method.invoke(producer, money*0.8f);
                }
                return returnValue;
            }
        });

        cglibProducer.saleProduct(10000f);
    }
}

6.Spring的AOP(面向切面编程)

6.1 Spring的基础

  • 作用:在程序运行期间,不修改源码对已有的方法进行增强
  • 优势:
    • 减少重复代码
    • 提高开发效率
    • 维护方便

6.2 通知

  • 前置通知,后置通知,异常通知,最终通知
  • 环绕通知,环绕通知具有明确的切入点调用

6.3 Spring基于XML的基本配置

<!--    spring中基于xml的AOP配置步骤
        1、把通知Bean也交给Spring来管理
        2、使用aop:config标签表明开始Aop的配置
        3、使用aop:aspect标签表明开始配置切面
                id属性:是给切面提供一个唯一标识
                ref属性:是指定通知类bean的id
        4、在aop:aspect标签的内部使用对应标签来配置通知的类型
            我们现在的示例是让printLog方法在切入点方法执行之前;所以使用前置通知
            aop:before: 表示配置前置通知
                method属性:用于指定logger类中那个方法是前置通知
                pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强-->
<!--    配置AOP-->
    <aop:config>
<!--        配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
<!--            配置通知的类型,并且建立通知方法和切入点方法的关联-->
            <aop:before method="printLog" pointcut="execution(public void com.ljh.service.Impl.AccountServiceImpl.saveAccount())"></aop:before>
        </aop:aspect>
    </aop:config>

6.4 切入点表达式(需要aspectj的Maven包)

<!--            切入点表达式的写法:
                关键字:execution(表达式)
                表达式:
                    访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
                标准的表达式写法:
                    public void com.ljh.service.impl.AccountServiceImpl.saveAccount()
                访问修饰符可以省略
                    void com.ljh.service.impl.AccountServiceImpl.saveAccount()
                返回值可以使用通配符,表示任意返回值
                    * com.ljh.service.impl.AccountServiceImpl.saveAccount()
                包名可以用通配符表示任意包。但是有几级包,就需要写几个*
                    * *.*.*.*.AccountServiceImpl.saveAccount()
                包名可以使用..表示当前包及其子包
                    * *..AccountServiceImpl.saveAccount()
                类名和方法名都可以使用*来实现统配
                    * *..*.saveAccount()
                方法名也可以省略
                    * *..*.*()  注,这个()里面没有参数,表示全部无参方法
                参数列表:
                    可以直接写数据类型:
                        基本类型直接写名称  int
                        引用类型写包名.类名的方式 java.lang.String
                   * *..*.*(*)  可以使用通配符表示任意类型,但是必须是有参的
                可以使用..表示有无参数均可,有参数可以是任意参数
                全通配写法
                    * *..*.*(..)

               实际开发中切入点表达式的通常写法:
                    切到业务层实现类下的所有方法
                        * com.ljh.service.Impl.*.*(..)
                -->

6.5 配置XML的各种通知(前后异常最终)


<!--    配置AOP-->
    <aop:config>
<!--        配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--配置前置通知:在切入点方法执行之前执行
            <aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>-->
            
            <!--配置后置通知:在切入点方法正常执行之后执行
            <aop:after-returning method="afterReturningPrintLog" pointcut="execution(* com.ljh.service.Impl.*.*(..))"></aop:after-returning>-->
            
            <!--配置异常通知:在切入点方法执行产生异常之后执行
            <aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(* com.ljh.service.Impl.*.*(..))"></aop:after-throwing>-->
            
            <!--配置前置通知:无论切入点方法是否正常执行他都会在其后面执行
            <aop:after method="afterPrintLog" pointcut="execution(* com.ljh.service.Impl.*.*(..))"></aop:after>-->

            <!--配置环绕通知-->
            <aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>

            <!--配置切入点表达式 id属性适用于指定表达式的唯一标识,expression属性用于指定表达式内容
                此标签写在aop:aspect内部,只能当前切面使用
                它还可以写在aop:aspect外面,此时就变成了所有切面可用。但是必须在切面之前-->
            <aop:pointcut id="pt1" expression="execution(* com.ljh.service.Impl.*.*(..))"/>
        </aop:aspect>
    </aop:config>
  • aop:pointcut标签可以简化切入点表达式的写法,直接可以引用pt1即可,不用每次引用切入点表达式

  • 后置通知和异常通知永远只能执行一个

6.6 环绕通知

    /**
     * 环绕通知
     *      问题:
     *          当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
     *      分析:
     *          通过对比动态代理中的环绕通知代码,发现动态代理中的环绕通知有明确的切入点方法调用,而我们的代码里面没有
     *      解决:
     *          Spring框架为我们提供了一个接口,ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明
     *          确的调用了切入点方法。该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类
     *          供我们使用
     * Spring中的环绕通知:
     *      他是spring框架为我们提供的一种可以在代码中手动控制增强方法可是执行的方式
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object returnValue = null;
        try {
            Object[] args = pjp.getArgs();//得到方法运行所需要的参数
            System.out.println("环绕logger类中的around方法开始执行日志了.前置");
            returnValue=pjp.proceed(); //明确调用业务层方法(切入点异常)
            System.out.println("环绕logger类中的around方法开始执行日志了,后置");
            return returnValue;
        } catch (Throwable e) { //必须要写Throwable,Exception拦不住
            e.printStackTrace();
            System.out.println("环绕logger类中的around方法开始执行日志了,异常");
            throw new RuntimeException(e);
        }finally {
            System.out.println("环绕logger类中的around方法开始执行日志了,最终");
        }
    }

6.7 基于注解的AOP

/**
 * 用于记录日志的工具类,他里面提供了公共的代码
 */
@Component("logger")
@Aspect                 //表示当前类是一个切面类
public class Logger {

    //定义一个切入点表达式,直接是一个方法
    @Pointcut("execution(* com.ljh.service.Impl.*.*(..))")
    private void pt1(){}
    /**
     * 前置通知 这个pt1必须加括号
     */
    //@Before("pt1()")
    public void beforePrintLog(){
        System.out.println("前置通知logger类中的printlog方法开始执行日志了");
    }
    /**
     * 后置通知
     */
   // @AfterReturning("pt1()")
    public void afterReturningPrintLog(){
        System.out.println("后置通知logger类中的printlog方法开始执行日志了");
    }
    /**
     * 异常通知
     */
    //@AfterThrowing("pt1()")
    public void afterThrowingPrintLog(){
        System.out.println("异常通知logger类中的printlog方法开始执行日志了");
    }
    /**
     * 最终通知
     */
    //@After("pt1()")
    public void afterPrintLog(){
        System.out.println("最终通知logger类中的printlog方法开始执行日志了");
    }

    /**
     * 环绕通知
     */
    @Around("pt1()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object returnValue = null;
        try {
            Object[] args = pjp.getArgs();//得到方法运行所需要的参数
            System.out.println("环绕logger类中的around方法开始执行日志了.前置");
            returnValue=pjp.proceed(); //明确调用业务层方法(切入点异常)
            System.out.println("环绕logger类中的around方法开始执行日志了,后置");
            return returnValue;
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("环绕logger类中的around方法开始执行日志了,异常");
            throw new RuntimeException(e);
        }finally {
            System.out.println("环绕logger类中的around方法开始执行日志了,最终");
        }
    }
}

  • xml文件

  • <?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: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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--    配置spring创建容器时要扫描的包-->
        <context:component-scan base-package="com.ljh"></context:component-scan>
    
    <!--    配置spring开启注解aop的支持-->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    
问题

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8cEjpUKJ-1675607345085)(C:\Users\11969\AppData\Roaming\Typora\typora-user-images\image-20230205204841069.png)]

  • Spring在只用注解开发的顺序选择上面存在问题

  • 使用环绕通知可以避免这个问题

  • 使用注解 推荐使用环绕通知

7.Spring中的JdbcTemplate

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l884eLxW-1675607345086)(C:\Users\11969\AppData\Roaming\Typora\typora-user-images\image-20230205205410723.png)]

7.1 作用

  • 他就是用于和数据库进行交互的,实现对表的CRUD操作

7.2 如何创建该方法

  • JdbcTemplate中的jar包依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
    </dependencies>
  • bean.xml的配置
<?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 id="accountDao" class="com.ljh.dao.Impl.AccountDaoImpl">
<!--        <property name="jt" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    配置jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    配置数据源-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///ljh01"></property>
        <property name="username" value="root"></property>
        <property name="password" value="021012"></property>
    </bean>
</beans>

7.3 Spring中的事务控制例子

7.3.1 基于XML

<!--    配置事务管理器-->
    <bean id="txManager" class="com.ljh.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"></property>
    </bean>

<!--    配置aop-->
    <aop:config>
<!--        配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.ljh.service.Impl.*.*(..))"/>
        <aop:aspect id="txAdvice" ref="txManager">
<!--            配置前置通知,开启事务-->
            <aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
<!--            配置后置通知,提交事务-->
            <aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
<!--            配置异常通知,回滚-->
            <aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
<!--            配置最终通知,释放事务-->
            <aop:after method="release" pointcut-ref="pt1"></aop:after>
        </aop:aspect>
    </aop:config>
7.3.2 基于注解
@Component("txManager")
@Aspect
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(* com.ljh.service.Impl.*.*(..))")
    public void pt1(){}

    /**
     * 等待注入
     * @param connectionUtils
     */
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtils.getThreadConnection().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtils.getThreadConnection().rollback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     */
    public void release(){
        try {
            connectionUtils.getThreadConnection().close();//还回连接池
            connectionUtils.removeConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Around("pt1()")
    public Object go(ProceedingJoinPoint pjp){
        Object returnValue = null;
        try{
            Object[] args = pjp.getArgs();
            beginTransaction();
            returnValue= pjp.proceed();
            commit();
            return returnValue;
        }catch (Throwable e){
            e.printStackTrace();
            rollback();
            throw new RuntimeException(e);
        }finally {
            release();
        }
    }
}
  • 不能使用前后异常和最终来使用,因为最终通知会在最后通知之前使用,导致关闭连接不能回滚
  • 所以我们使用环绕通知来实现

8.Spring的事务控制

8.1 基于XML文件配置

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--        配置账户的持久层-->
    <bean id="accountDao" class="com.ljh.dao.Impl.AccountDaoImpl">
<!--        <property name="jt" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    配置业务层-->
    <bean id="accountService" class="com.ljh.service.Impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

<!--    配置数据源-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///ljh01"></property>
        <property name="username" value="root"></property>
        <property name="password" value="021012"></property>
    </bean>

    <!--spring中基于xml的声明式事务控制配置步骤
        1,配置事务管理器
        2,配置事务的通知
            此时我们需要导入事务的约束 tx名称空间和约束,同时也需要AOP的
            使用tx:advice标签配置事务通知
                属性:
                    id:给事务通知起一个标志
                    transaction-manager:给事务通知提供一个事务管理器的引用
        3,配置AOP中的通用切入点表达式:
        4,建立事务通知和切入点表达式的关系
        5,配置事务的属性
                是在事务的通知tx:advice标签的内部
        -->

<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--配置事务的属性
            isolation="" :事务的隔离级别,默认值是DEFAULT,表示使用数据库的默认隔离级别
            propagation="" :用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,REQUIRED可以用增删改的选择。查询方法可以选择SUPPORTS
            timeout="":用于指定事务的超时时间。默认值是-1,表示永不超时。如果指定了数值,以秒为单位
            read-only="":用于指定事务是否可读。只有查询方法才能设置true。默认值为false,表示读写
            rollback-for="":用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚
            no-rollback-for="":用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚,没有默认值,表示任何异常都回滚
            -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置切入点表达式-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.ljh.service.Impl.*.*(..))"/>
        <!--    建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>

8.2 基于注解的事务配置

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

<!--    配置spring穿件容器是要扫描的包-->
    <context:component-scan base-package="com.ljh"></context:component-scan>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    配置数据源-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///ljh01"></property>
        <property name="username" value="root"></property>
        <property name="password" value="021012"></property>
    </bean>

    <!--spring中基于xml的声明式事务控制配置步骤
        1,配置事务管理器
        2,开启spring对注解事务的支持@Transactional
        3,在需要事务支持的地方使用@Transactional注解
        -->

<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!--    配置spring穿件容器是要扫描的包-->
    <context:component-scan base-package="com.ljh"></context:component-scan>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    配置数据源-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///ljh01"></property>
        <property name="username" value="root"></property>
        <property name="password" value="021012"></property>
    </bean>

    <!--spring中基于xml的声明式事务控制配置步骤
        1,配置事务管理器
        2,开启spring对注解事务的支持@Transactional
        3,在需要事务支持的地方使用@Transactional注解
        -->

<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dateSource"></property>
    </bean>

<!--    开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

9 Spring的Junit结合

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ="classpath:bean.xml")
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值