ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

第四次总结

2021-07-18 23:58:42  阅读:128  来源: 互联网

标签:总结 spring 代理 bean 注解 方法 public 第四次


第四次总结

所学内容:

第一天

1.spring的概述

1.1spring是什么

​ Spring是分层的Java SE/EE 应用full-stack轻量级开源框架,以Ioc(Inverse Of Control:反转控制)和AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层SpringMVC和持久层Spring JDBC以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的Java EE企业应用开源框架。

1.2spring的两大核心

​ IoC和AOP

1.3spring的发展历程和优势

1.4spring体系结构

2.程序的耦合以及解耦

/*程序的耦合
   耦合:程序间的依赖关系
       包括:
           类之间的依赖
           方法间的依赖
   解耦:
       降低程序间的依赖关系
   实际开发中:
       应该做到:编译期不依赖,运行时才依赖。
   解耦的思路:
       第一步:使用反射来创建对象,而避免使用new关键字。
       第二步:通过读取配置文件来获取要创建的对象全限定类名
       
       创建在resources文件夹下的properties最后会成为类根路径下的文件
       */

3.IoC概念和spring中的IoC

3.1.IoC控制反转:

​ 把创建对象的权利交给框架,是框架的重要特征,并非面向对象编程的专用术语,它包含依赖注入(Dependency Injection,DI)和依赖查找(Dependency Lookup)

3.2.IoC的作用:削减计算机程序的耦合(降低依赖关系)

3.3.配置文件:

​ 配置文件名字不强制,不能是中文

<?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">
    
</beans>

3.4.ApplicationContext的三个实现类

public class Client {

    /**
     * 获取是spring的Ioc核心容器,并根据id获取对象
     *
     * ApplicationContext的三个常用实现类
     *      ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的话,加载不了。
     *      FileSystemXmlApplicationContext:它可以加载任意路径下的配置文件(必须有访问权限)
     *      AnnotationConfigApplicationContext:它是用于读取注解创建容器的
     *
     * 核心容器的两个接口引发的问题:
     * ApplicationContext:     单例对象适用         采用此接口
     *          它在构建核心容器时,创建对象采取的策略时采用立即加载的方式,也就是说,只要一读取完配置文件马上创建配置文件中配置的对象。
     * BeanFactory:             多例对象适用
     *          它在构建核心容器时,创建对象采取的策略时采用延迟加载的方式,也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。
     *
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        ApplicationContext ac = new FileSystemXmlApplicationContext("D:\\idea\\BackEnd\\SSM\\Spring\\day01_03_spring\\src\\main\\resources\\bean.xml");
        //2.根据id获取Bean对象,两种方式都可以
        /*IAccountService service = (IAccountService) ac.getBean("accountService");
        IAccountDao accountDao = ac.getBean("accountDao",IAccountDao.class);

        System.out.println(service);
        System.out.println(accountDao);*/

        //--------BeanFactory

        BeanFactory factory = new XmlBeanFactory(new ClassPathResource("bean.xml"));
        IAccountService service = (IAccountService) factory.getBean("accountService");
        IAccountDao accountDao = factory.getBean("accountDao",IAccountDao.class);

        System.out.println(service);
        System.out.println(accountDao);
    }

}

3.5.spring对bean的管理细节

<?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">
<!--   把对象的创建交给spring来管理 -->
<!--    spring对bean的管理细节
        1.创建bean的三种方式
        2.bean对象的作用范围
        3.bean对象的生命周期
-->

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


<!--    第二种方式:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)-->
    <!--<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>-->

<!--    第三种方式:使用工厂中的静态方法创建对象,(使用某个类中的静态方法创建对象,并存入spring容器)
    <bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>-->

<!--    bean的作用范围调整
        bean标签的scope属性:
            作用:用于指定bean的作用范围
            取值:
                singleton:单例的(默认值)
                prototype:多例的
                request:作用于web应用的请求范围
                session:作用于web应用的会话范围
                global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session



    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="singleton"></bean> -->

<!--    bean对象的生命周期
        单例对象
            出生:当容器创建时对象出生
            活着:只要容器还在,对象一直活着
            死亡:容器销毁,对象消亡
            总结:单例对象的生命周期和容器相同

        多例对象
            出生:当使用对象时spring框架为我们创建
            活着:对象只要在使用过程中就一直活着
            死亡:当对象长时间不用,且没有别的对象引用时,由java的垃圾回收器回收
        -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"
    init-method="init" destroy-method="destroy"></bean>



</beans>

4.依赖注入(Dependency Injection)

<?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">

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

        -->

<!--    构造函数注入:
        使用标签:constructor-arg
        标签出现的位置:bean标签的内部
        标签中的属性:
            type:用于指定要注入的数据类型,该数据类型也是构造函数中某个或某些参数的类型
            index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引的位置是从0开始
            name:用于指定给构造函数中指定名称的参数赋值    常用的
            ===以上三个用于指定给构造函数中哪个参数赋值===
            value:用于给基本类型和String类型的数据
            ref:用于指定其它的bean类型数据,它指的就是在spring的Ioc核心容器中出现过的bean对象

        优势:
            在获取bean对象时,注入数据时必须的操作,否则对象无法创建成功
        弊端:
            改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。
        -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype">
        <constructor-arg name="name" value="泰斯特"></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>

<!--    set方法注入                 更常用的方式
        涉及的标签:property
        出现的位置:bean标签的内部
        标签的属性
            name:用于指定注入时所调用的set方法名称
            value:用于提供基本类型和String类型的数据
            ref:用于指定其他的bean类型数据,它指的就是在spring的Ioc核心容器总出现过的bean对象
        优势:
            创建对象时没有明确的限制,可以直接使用默认构造函数
        弊端:
            获取对象时,有可能成员变量没有赋值

-->
    <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="name" value="test"></property>
        <property name="age" value="21"></property>
<!--        <property name="birthday" ref="now"></property>-->
    </bean>


<!--    复杂类型的注入/集合类型的注入
        用于给list结构集合注入的标签:list,array,set
        用于给Map结构结婚注入的标签:map,props
        结构相同,标签可以互换
-->
    <bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <array>
                <value>AAA</value>
                <value>AAA</value>
                <value>AAA</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>AAA</value>
                <value>AAA</value>
                <value>AAA</value>
            </list>
        </property>

        <property name="mySet">
            <set>
                <value>AA1</value>
                <value>AA2</value>
                <value>AA3</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>

</beans>

第二天:基于注解的IoC以及IoC的案例

1.spring中IoC的常用注解

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: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.itheima"></context:component-scan>


</beans>

java

/**
 * 账户的业务层实现类
 *
 * xml的配置
 * <bean id="accountService" class="com.itheima.impl.AccountServiceImpl"
 *  scope="" init-method="" destroy-method="">
 *      <property name="" value=""|ref=""></property>
 *  </bean>
 *
 *  用于创建对象的
 *      他们的作用就和在xml配置文件中编写一个<bean></bean>标签实现的功能是一样的
 *      @Component
 *          作用:用于把当前类对象存入spring容器中
 *          属性:
 *              value:用于指定bean的id,当我们不写时,它的默认值就是当前类名,且首字母改小写
 *      @Constroll      一般用在表现层
 *      @Service        一般用在业务层
 *      @Repository     一般用在持久层
 *      以上三个注解他们的作用和属性于Component是一模一样的。
 *      他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更清晰
 *  用于注入数据的
 *      他们的作用就和在xml配置文件中的bean标签中写一个property标签的作用是一样的
 *      Autowired:
 *          作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *              如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错
 *              如果ioc容器中有多个类型匹配时:会根据名称匹配,当没有匹配的名称时会报错
 *          出现位置:
 *              可以是变量上,也可以是方法上
*           细节:
 *              在使用注解注入时,set方法就不是必须的了。
 *
 *      Qualifier:
 *          作用:在按照类中注入的基础之上再按照名称注入,它再给类成员注入时不能单独使用。但是在给方法参数注入时可以
 *          属性:
 *              value:用于指定注入bean的id
 *      Resource
 *          作用:直接按照bean的id注入,它可以单独使用
 *          属性:
 *              name:用于指定bean的id
 *       以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
 *       另外,集合类型的注入只能通过xml来实现
 *
 *       Value
 *              作用:用于注入基本类型和String类型的数据
 *              属性:
 *                  value:用于指定数据的值,它可以使用spring中的SpEL(也就是spring的el表达式)
 *                         SpEL的写法:${表达式}
 *  用于改变作用范围的
 *      他们的作用就和在bean标签中使用scope属性实现的功能是一样的
 *      Scope:
 *          作用:用于指定bean的作用范围
 *          属性:
 *              value:指定范围的取值。常用取值:singleton,prototype
 *
 *  和生命周期相关的,了解
 *      他们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的
 *      PreDestroy
 *          作用:用于指定销毁方法
*       PostConstruct
 *          作用:用于指定初始化方法
 */

@Component
@Scope("singleton")
public class AccountServiceImpl implements IAccountService {

    /*@Autowired
    @Qualifier("accountDao2")*/
    @Resource(name = "accountDao2")
    private IAccountDao accountDao1;

    @PostConstruct
    public void init(){
        System.out.println("初始化方法执行力");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("销毁方法执行力");
    }

    public AccountServiceImpl(){
        System.out.println(accountDao1);
    }


    @Override
    public void saveAccount() {
        accountDao1.saveAccount();
    }



}

2.案例使用xml方式和注解方式实现单表的CRUD操作

​ 持久层技术选择:dbutils

3.改造基于注解的ioc案例,使用纯注解的方式实现

​ spring的一些新注解

SpringConfiguration

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * spring中的新注解
 * Configuration
 *      作用:指定当前类是一个配置类
 *      细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,可以不写,可以传入多个参数
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
 *                  我们使用此注解就等同于在xml中配置了:
 *                      <context:component-scan base-package="com.itheima"></context:component-scan>
 *      @Bean
 *          作用:用于把当前方法的返回值作为bean对象存入spring得到的ioc容器中
 *          属性:
 *              name:用于指定bean的id,当不写时,默认值是当前方法的名称
 *          细节:
 *              当我们使用注解配置方法时,如果方法有参数,spring框架回去容器中查找有没有可用的bean对象。
 *              查找的方式和Autowired注解的方式是一样的。
 *      @Import
 *          作用:用于导入其他的配置类,导入的配置类不需要配置Configuration注解
 *          属性:
 *              value:用于指定其他配置类的字节码。
 *                      当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
 *
 *      @PropertySource
 *          作用:用于指定properties文件的位置
 *          属性:
 *              value:指定文件的名称和路径。
 *                  关键字:classpath。表示类路径下
 */

@Configuration
//@ComponentScan(basePackages = {"com.itheima"})
//@ComponentScan(basePackages = "com.itheima")
//@Scope("prototype")//当没有Configuration注解并且值为prototype时会报错
@ComponentScan({"com.itheima"})
@PropertySource("classpath:druid.properties")
@Import(JdbcConfig.class)
public class SpringConfiguration {


}

JdbcConfig

//@Configuration
public class JdbcConfig {
//    不加前缀可能会读到别的配置,例如username读成lenovo
    @Value("${jdbc.driverClassName}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
//     不要乱加注解,会影响执行的顺序
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);

    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DruidDataSource ds = new DruidDataSource();

        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;

    }

}

Test

AnnotationConfigApplicationContext ca = new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService service = ca.getBean("accountService",IAccountService.class);

4.spring和Junit整合

​ 1.应用程序的入口:main方法

​ 2.junit单元测试中没有main方法也能执行
​ junit集成了一个main方法
​ 该方法就会判断当前测试类中哪些方法有@Test注解
​ junit就让有Test注解的方法执行

​ 3.junit不会管我们是否采用spring框架
​ 在执行测试方法时,junit根本不知道我们是不是使用了spring框架
​ 所以也就不会为我们读取配置文件/配置类创建spring核心容器
​ 4.由以上三点可知
​ 当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入

package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import myconfig.SpringConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Spring整合junit配置
 *      1.导入spring整合junit的jar(坐标)
 *      2.使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
 *              @RunWith
 *      3.告知spring运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
 *              @ContextConfiguration
 *                  locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *                  classes:指定注解类所在的位置
 *      当我们使用spring5.x版本的时候,要求junit的jar必须是4.12及以上
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {


    @Autowired
    private IAccountService service = null;

    @Test
    public void testFindAll(){
        List<Account> allAccount = service.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }


    }

    @Test
    public void testFindOne(){
        Account account = service.findAccountById(1);
        System.out.println(account);

    }

    @Test
    public void testSave(){

        Account account = new Account();
        account.setName("张三");
        account.setMoney(123456f);
        service.saveAccount(account);

    }

    @Test
    public void testUpdate(){

        Account account = new Account();
        account.setId(4);
        account.setName("罗翔");
        account.setMoney(123456f);
        service.updateAccount(account);
    }

    @Test
    public void testDelete(){


        service.deleteAccount(5);
    }

}

第三天:AOP

1.动态代理

1.1.基于接口的动态代理

package com.itheima.proxy;

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

/**
 * 模拟一个消费者
 */
public class Client {

    public static void main(String[] args) {
        final Producer producer = new Producer();

        /**
         * 动态代理:
         *  特点:字节码随用随创建,随用随加载
         *  作用:不修改源码的基础上对方法增强
         *  分类:
         *      基于接口的动态代理
         *      基于子类的动态代理
         *  基于接口的动态代理,该方式必须实现接口
         *      涉及的类,Proxy
         *      提供这:JDK官方
         *  如何创建代理对象:
         *      使用Proxy类中的newProxyInstance方法
         *  创建代理对象的要求
         *      被代理类最少实现一个接口,如果没有则不能使用
         *  newProxyInstance方法的参数:
         *      ClassLoader:类加载器
         *          它是用于加载代理对象字节码的,和被代理对象使用相同的类加载器。固定写法
         *      Class[]:字节码数组
         *          它是用于让代理对象和被代理对象有相同方法,固定写法。
         *      InvocationHandler:用于提供增强的代码
         *          它是让我们写如何代理。我们一般都是写一个该接口的实现类。通常情况下都是匿名内部类,但不是必须的
         *          此接口的实现类都是谁用谁写。
         */
        IProducer proxy = (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+"1";
                    }
                });
        System.out.println(proxy.saleProduct(10000f));


    }

}

1.2.基于子类的动态代理

package com.itheima.cglib;

import com.itheima.proxy.IProducer;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

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

/**
 * 模拟一个消费者
 */
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+"1";
            }
        });

        cglibProducer.saleProduct(12000f);

    }

}

2.AOP的概念

2.1.AOP概述

全称是 Aspect Oriented Programming 即:面向切面编程。简单点说就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的 基础上,对我们的已有方法进行增强。

2.2. AOP 的作用及优势

作用: 在程序运行期间,不修改源码对已有方法进行增强。

优势: 减少重复代码 提高开发效率 维护方便

2.3.AOP的实现方式

使用动态代理技术

3.spring中AOP相关术语

Joinpoint(连接点):
所谓连接点是指那些被拦截到的点,在spring中,连接点指的是方法,因为spring只支持方法类型的连接点。(如sevice中的方法)

Pointout(切入点):
切入点是指我们要对哪些Joinpoint进行拦截的定义。(被增强的方法,它一定是连接点)

Advice(通知/增强):
所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。 通知的类型:前置通知,后置通知,异常通知, 最终通知,环绕通知。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KQc1FrCN-1626623559812)(C:\Users\lenovo\Desktop\SSM框架\Spring\03-第三天\截图\通知的类型.jpg)]

Introduction(引介):
引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方 法或 Field。

Target(目标对象): 代理的目标对象。

Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而 AspectJ 采用编 译期织入和类装载期织入。

Proxy(代理): 一个类被 AOP 织入增强后,就产生一个结果代理类。

Aspect(切面): 是切入点和通知(引介)的结合。

4.spring中要明确的事

​ a、开发阶段(我们做的) 编写核心业务代码(开发主线):大部分程序员来做,要求熟悉业务需求。 把公用代码抽取出来,制作成通知。(开发阶段最后再做):AOP 编程人员来做。 在配置文件中,声明切入点与通知间的关系,即切面。:AOP 编程人员来做。

​ b、运行阶段(Spring 框架完成的) Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对 象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

5.spring中基于XML和注解的AOP配置

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"
       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">

    

</beans>

标签:总结,spring,代理,bean,注解,方法,public,第四次
来源: https://blog.csdn.net/m0_46217260/article/details/118885708

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有