【Spring】---学习笔记

【Spring】---学习笔记

一、Spring

1、简介

image-20210816111538651

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.2</version>
</dependency>

2、优点

  • Spring是一个开源的免费的框架(容器)
  • Spring是一个轻量级的,非侵入式的框架
  • 控制反转(IOC Inversion of Control 和面向切面编程(AOP Aspect Oriented Programming
  • 支持事务的处理,对框架整合的支持!

总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!

3、组成

在这里插入图片描述

  • Spring-Core:Core包是框架的最基础部分,并提供依赖注入(Dependency Injection)管理Bean容器功能。这里的基础概念是BeanFactory,它提供对Factory模式的经典实现来消除对程序性单例模式的需要,并真正地允许你从程序逻辑中分离出依赖关系和配置。

  • Spring-Context:核心模块的BeanFactory使Spring成为一个容器,而上下文模块使它成为一个框架。这个模块扩展了BeanFactory的概念,增加了消息、事件传播以及验证的支持。另外,这个模块提供了许多企业服务,例如电子邮件、JNDI访问、EJB集成、远程以及时序调度(scheduling)服务。也包括了对模版框架例如Velocity和FreeMarker集成的支持。

  • Spring-Aop:Spring在它的AOP模块中提供了对面向切面编程的丰富支持。例如方法拦截器(servletListener ,controller....)和切点,可以有效的防止代码上功能的耦合,这个模块是在Spring应用中实现切面编程的基础。Spring的AOP模块也将元数据编程引入了Spring。使用Spring的元数据支持,你可以为你的源代码增加注释,指示Spring在何处以及如何应用切面函数。

  • Spring-Dao:使用JDBC经常导致大量的重复代码,取得连接、创建语句、处理结果集,然后关闭连接、旧代码中迁移自定义工具类JDBCUtil 也让开发变得繁琐。Spring的Dao模块对传统的JDBC进行了抽象,还提供了一种比编程性更好的声明性事务管理方法。

  • Spring-Web:Web上下文模块建立于应用上下文模块之上,提供了WEB开发的基础集成特性,例如文件上传。另外,这个模块还提供了一些面向服务支持。利用Servlet listeners进行IOC容器初始化和针对Web的applicationcontext。

  • Spring Web MVC:(Model-View-Controller)Spring为构建Web应用提供了一个功能全面的MVC框架。它提供了一种清晰的分离模型,在领域模型代码和web form之间。并且,还可以借助Spring框架的其他特性。

  • Spring-ORM:关系映射模块,ORM包为流行的“关系/对象”映射APIs提供了集成层,包括JDO,Hibernate和iBatis(MyBatis)。通过ORM包,可以混合使用所有Spring提供的特性进行“对象/关系”映射,方便开发时小组内整合代码。

4、拓展

image-20210816113003272

image-20210816113024096

image-20210816113041941

二、IOC理论推导

控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。

1、业务代码案例

1、UserDao接口

2、UserDaoImpl实现类

3、UserService业务接口

4、UserServiceImpl业务实现类

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码,如果程序代码量十分大,修改一次的成本价十分昂贵。

我们使用一个Set接口实现。已经发生了革命性的变化!

dao层:UserDao.java

public interface UserDao {
    void getUser();
}

dao层实现类1:UserDaoImpl

public class UserDaoImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("默认获取用户的数据!");
    }
}

dao层实现类2:UserDaoMysqlImpl

public class UserDaoMysqlImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("Mysql获取用户数据!");
    }
}

业务层接口:

public interface UserService {
    void getUser();
}

业务层:UserServiceImpl.java重点分析

private UserDao userDao;


//    //接口的实例化,原来我们采取的是这种写死的方式。
//    private UserDao userDao = new UserDaoImpl();

	//引用IOC思想后
    //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

测试:

public class MyTest {
    public static void main(String[] args) {

        //用户实际调用的是业务层,dao层不需要接触。
        UserServiceImpl userService = new UserServiceImpl();

        userService.setUserDao(new UserDaoMysqlImpl());

        userService.getUser();

    }
}
  • 之前,程序是主动创建对象,控制权在程序员手上。
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!

这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注在业务的实现上。这就是IOC的原型!

2、IOC容器概述

  • IOC容器就是实现控制反转的容器,下图中可以看出把实体类对象和配置的xml文件(实例化的数据)都丢到容器里面,就会产生一个可以使用的完全配置好的系统。
  • 装配元数据有多种方法:注解或者xml文档。

image-20210816160637527

三、 HelloSpring--第一个Spring程序

1、创建一个实体类Hello

public class Hello {

    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

2、resouces下配置beans.xml

此处可以参考官方的文档

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用Spring来创建对象,在Spring这些都称为bean
        bean = 对象       new Hello()
        id = 变量名
        class = new的对象
        property 相当于给对象中的属性设置一个值
    -->
    <bean id="hello" class="com.darkerg.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>

</beans>

3、测试

public class MyTest {

    @Test
    public void test(){
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以。
        Hello hello = (Hello)context.getBean("hello");
        System.out.printf( hello.toString());

    }
}

4、思考:

  • Hello对象是谁创建的?

    Spring创建的

  • Hello对象的属性是怎么设置的?

    Hello对象的属性是由Spring容器设置的

  • 这个过程就叫做控制反转:

    控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring之后,对象是由Spring来创建的。

    反转:程序本身不创建对象,而变成被动的接收对象。

    依赖注入:就是利用set方法来进行注入的。

    IOC是一种编程的思想,由主动地编程变成被动的接收。

    对象由Spring来创建,管理,装配

四、IOC创建对象的方式

1、使用无参构造创建对象,默认!

2、假设我们要使用有参构造创建对象

  • 下标赋值
<!--下标赋值-->
    <bean id="user" class="com.dakerg.pojo.User">
       <constructor-arg index="0" value="asdjkl"/>
    </bean>
  • 通过类型创建
<bean id="user" class="com.dakerg.pojo.User">
    <constructor-arg type="java.lang.String" value="qweho"/>
</bean>
  • 通过参数名
<bean id="user" class="com.dakerg.pojo.User">
    <constructor-arg name="name" value="asdnzxmcqwe"/>
</bean>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!

五、 Spring配置说明

1、别名

<!-- 别名 -->
<alias name="user" alias="user2"/>

<!--或者通过name属性取多个别名-->
<bean id="user" class="com.dakerg.pojo.User" name="u1,u2">
        <constructor-arg name="name" value="asdnzxmcqwe"/>
    </bean>

2、Bean的配置

<!--使用spring来创建对象,在spring这些都是bean-->
<bean id="hello" class="com.xiaofan.pojo.Hello" name="hello2, h2">
    <property name="name" value="spring..."/>
</bean>

3、Import

一般用于团队开发使用,它可以将多个配置文件合并为一个

假设,现在项目中有多个人开发:这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的

  • 张三

  • 李四

  • 王五

  • applicationContext.xml

    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
    

使用的时候,直接使用总的配置就可以了

六、Dependency Injection依赖注入

1、构造器注入

2、通过Set方式注入【重点】

  • 依赖注入:Set注入!
    • 依赖:bean对象的创建依赖于容器!
    • 注入:bean对象中的所有属性,由容器来注入!

【环境搭建】

1.复杂类型

2.真实测试对象

Student实体类

import lombok.Data;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

@Data
public class Student {

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

}

Address实体类

import lombok.Data;

@Data
public class Address {
    private String address;
}

注入

<bean id="address" class="com.darkerg.pojo.Address">
        <property name="address" value="地球村中国!"/>
    </bean>

    <bean id="student" class="com.darkerg.pojo.Student">
        <!--第一种:普通值注入value-->
        <property name="name" value="darkerg"/>
        <!--第二种,bean注入,ref-->
        <property name="address" ref="address"/>
        <!--第三种,数组注入,array-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--第四种,List注入,list-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>
        <!--第五种,Map注入,map-->
        <property name="card">
            <map>
                <entry key="身份证" value="123456789796"/>
                <entry key="校园卡" value="201856435"/>
            </map>
        </property>
        <!--第六种,Set注入,set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>
        <!--第七种,空值注入,-->
        <!-- <property name="wife" value=""/>-->
        <property name="wife">
            <null></null>
        </property>

        <!--第八种,properties,props-->
        <property name="info">
            <props>
                <prop key="学号">1237893274</prop>
                <prop key="性别">男</prop>
                <prop key="班级">2019122345</prop>
            </props>
        </property>
    </bean>

测试

@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        Student student = (Student) context.getBean("student");

        System.out.printf( student.toString());
    }

3、拓展方式注入

我们可以使用p命名空间和c命名空间进行注入:

注意要添加相关xml约束配置,c命名空间注入还需要有参构造器。

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

    <!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.darkerg.pojo.User" p:name="darkerg" p:age="18"/>

    <!--p命名空间注入,通过构造器注入:constructs-args-->
    <bean id="user2" class="com.darkerg.pojo.User" c:age="18" c:name="asdkjl"/>

</beans>

测试

ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);
System.out.printf(user.toString());

4、bean的作用域

image-20210816200813285

1、单例模式(Spring默认机制)

<bean id="user2" class="com.darkerg.pojo.User" c:age="18" c:name="asdkjl" scope="singleton"/>

2、原型模式:每次从容器中get的时候,都会产生一个新的对象。

<bean id="user2" class="com.darkerg.pojo.User" c:age="18" c:name="asdkjl" scope="prototype"/>

3、其余的request、session、application这些个只能在web开发中使用到!

七、Bean的自动装配

  • 自动装配是Spring满足bean依赖的一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性。

在Spring中有三种装配的方式

1、在xml中显式的配置

2、在Java中显式配置

3、隐式的自动装配bean【重要】

1、测试

1、环境搭建:一个人有两个宠物(三个类)

@Data
public class People {

    private Cat cat;
    private Dog dog;
    private String name;

}

2、ByName自动装配

<bean id="cat" class="com.darkerg.pojo.Cat"/>
<bean id="dog" class="com.darkerg.pojo.Dog"/>
<!-- 
    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
-->
<bean id="people" class="com.darkerg.pojo.People" autowire="byName">
     <property name="name" value="darkerg"/>
</bean>

3、ByType自动装配

<!-- 
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
-->
<bean id="people" class="com.darkerg.pojo.People" autowire="byType">
     <property name="name" value="darkerg"/>
</bean>

小结:

  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。

4、使用注解自动装配

jdk1.8支持的注解,Spring2.5就支持注解了。

要是用注解须知:

  • 导入约束:context约束

  • 配置注解的支持:context:annotation-config/

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config/>
    
    </beans>
    

@Autowired

直接在属性上使用即可!也可以在set方式上使用。

使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符号名字byName!

科普:

@Nullable	字段标记了这个注解,说明这个字段可以为Null;
public @interface Autowired {
    boolean required() default true;
}

测试代码:

//如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空。
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")去配合@Autowired的使用,指定一个唯一的bean对象注入!

@Resource

public void People{
	
	@Resource(name = "cat2")
	private Cat cat;
	
	@Resource
	private Dog dog;
}

小结:@Resource与@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上。
  • @Autowired默认通过byType的方式实现
  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!

八、使用注解开发

在Spring4之后,要是用注解开发,必须要保证AOP的包导入了。

image-20210816212548265

使用注解需要导入context约束,增加注解的支持。

1、bean

@Component:

组件,放在类上,说明这个类被Spring管理了,就是bean!默认的名字是类名的小写。

2、属性如何输注入

@Value("属性值")

放在属性上面,给属性赋值。也可以放在set方法上面。

3、衍生的注解

@Component有几个衍生注解,我们在web开发中,会按照MVC三层架构分层!

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】

这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean。

4、自动装配置

5、作用域

//等价于 <bean id="user" class="com.darkerg.pojo.User"/>
//@Component组件
@Component
@Scope("prototype")
public class User {

    @Value("adsjkl")
    public String name ;
}

6、小结

​ xml与注解:

  • xml更加万能,适用于任何场合!维护简单方便。
  • 注解 不是自己的类使用不了,维护相对复杂。
  • xml用来管理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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.darkerg.pojo"/>
    <context:annotation-config/>

</beans>

九、使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做。

JavaConfig是Spring的一个子项目,在Spring 4 之后,它成为了一个核心功能。

image-20210816215109254

User.java

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Data
//这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中。
@Component
public class User {

    @Value("我是傻逼")//注入值
    private String name;

}

DarkergConfig.java配置类

import com.darkerg.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration//这个也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前看的beans.xml是一样的。
@ComponentScan("com.darkerg.pojo")//扫描
@Import(DarkergConfig2.class)//合并配置类
public class DarkergConfig {

    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入到bean的对象!
    }

}

MyTest.java测试类

public class MyTest {

    @Test
    public void test1(){

        //如果完全使用使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(DarkergConfig.class);

        User user = (User)context.getBean("getUser");

        System.out.printf( user.getName());

    }

}

这种纯Java的配置方式,在SpringBoot中随处可见!

十、代理模式

为什么要学习代理模式?

因为这就是SpringAOP的底层!【SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

QQ截图20210816221613

1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决。
  • 真是角色:被代理的角色。
  • 代理角色:代理真是角色后,我们一般会做一些附属操作。
  • 客户:访问代理对象的人。

代码步骤:

1.接口

public interface Rent {

    public void rent();

}

2.真实角色

public class Host implements Rent{

    @Override
    public void rent() {
        System.out.println("房东要出租房子!");
    }
}

3.代理角色

public class Proxy implements Rent{

    private Host host;

    public Proxy(){

    }

    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        seeHouse();
        host.rent();
        hetong();
        fee();
    }

    public void seeHouse(){
        System.out.println("中介带你看房");
    }

    public void fee(){
        System.out.println("收中介费");
    }

    public void hetong(){
        System.out.println("签合同");
    }
}

4.客户端访问代理角色

public class Client {

    public static void main(String[] args) {

        Host host = new Host();
        //代理
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }

}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共业务就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实角色就会产生一个代理角色;代码里会翻倍,开发效率会变低~

2、加深理解

image-20210817114546530

3、动态代理

产生原因:即想要有代理,但是还不想额外增加类,就用到了反射的机制!

  • 动态代理和静态代理角色一样

  • 动态代理的代理类是动态生成的,不是我们直接写好的。

  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理

    • 基于接口---JDK动态代理
    • 基于类:cglib
    • Java字节码实现:javasist

需要了解两个类:Proxy,InvocationHandler:调用处理程序

InvocationHandler接口

.InvocationHandler接口是proxy代理实例的调用处理程序实现的一个接口,每一个proxy代理实例都有一个关联的调用处理程序;在代理实例调用方法时,方法调用被编码分派到调用处理程序的invoke方法.

每一个动态代理类的调用处理程序都必须实现InvocationHandler接口,并且每个代理类的实例都关联到了实现该接口的动态代理类调用处理程序中,当我们通过动态代理对象调用一个方法时候,这个方法的调用就会被转发到实现InvocationHandler接口类的invoke方法来调用,看如下invoke方法:

 /**
    * proxy:代理类代理的真实代理对象com.sun.proxy.$Proxy0
    * method:我们所要调用某个对象真实的方法的Method对象
    * args:指代代理对象方法传递的参数
    */
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;

Proxy类

Proxy类就是用来创建一个代理对象的类,它提供了很多方法,但是我们最常用的是newProxyInstance方法。

public static Object newProxyInstance(ClassLoader loader, 
                                            Class<?>[] interfaces, 
                                            InvocationHandler h)

这个方法的作用就是创建一个代理类对象,它接收三个参数,我们来看下几个参数的含义:

  • loader:一个classloader对象,定义了由哪个classloader对象对生成的代理类进行加载
  • interfaces:一个interface对象数组,表示我们将要给我们的代理对象提供一组什么样的接口,如果我们提供了这样一个接口对象数组,那么也就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法。
  • h:一个InvocationHandler对象,表示的是当动态代理对象调用方法的时候会关联到哪一个InvocationHandler对象上,并最终由其调用。

Rent接口

public interface Rent {
    public void rent();
}

Host主人

public class Host implements Rent {

    @Override
    public void rent() {
        System.out.println("房东要出租房子!");
    }
}

调用处理程序

可以提取为一个工具类

//等会儿我们使用这个类,自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {
    //提取为工具类
    //private Object target;
    
    //public void setTarget(Object target){
    //	this.target = target;
	//}

    //被代理的接口
    private Rent rent;

    public void setRent(Rent rent) {
        this.rent = rent;//实例化接口
    }

    //生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this);
    }

    //处理代理实例并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        seeHouse();
        //动态代理的本质,就是通过反射机制实现!
        Object result = method.invoke(rent, args);
        fee();

        return result;
    }

    public void seeHouse(){
        System.out.println("中介带看房子");
    }

    public void fee(){
        System.out.println("收中介费");
    }
}

Client

public class Client {

    public static void main(String[] args) {
        //真实角色
        Host host = new Host();

        //代理角色:现在没有
        ProxyInvocationHandler pih = new ProxyInvocationHandler();//这里的proxy就是动态生成的,我们并没有写!
        //通过调用程序处理角色来处理我们要调用的接口对象!
        pih.setRent(host);

        Rent proxy = (Rent) pih.getProxy();

        proxy.rent();

    }

}

十一、AOP

1、什么是AOP?

OP为(Aspect Oriented Programming)的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

image-20210817130343704

2、Aop在Spring中的作用

image-20210817130625060

image-20210817130748555

3、使用Spring实现AOP

【重点】使用AOP,需要导入的依赖包。

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
</dependency>

方式一:使用Spring的API接口【主要是SpringAPI接口实现】

UserService接口

public interface UserService {

    public void add();
    public void delete();
    public void update();
    public void select();

}

UserServiceImpl实现类

public class UserServiceImpl implements UserService{

    @Override
    public void add() {
        System.out.println("增加了一个用户");
    }

    @Override
    public void delete() {
        System.out.println("删除了一个用户");
    }

    @Override
    public void update() {
        System.out.println("更新了一个用户");
    }

    @Override
    public void select() {
        System.out.println("查询了一个用户");
    }
}

前置日志log

import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {

    @Override
    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    public void before(Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

后置日志afterLog

import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {

    @Override
    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}

在Spring中注册

注意下面的配置

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--注册bean-->
    <bean id="userService" class="com.dakerg.service.UserServiceImpl"/>
    <bean id="log" class="com.dakerg.log.Log"/>
    <bean id="afterLog" class="com.dakerg.log.AfterLog"/>

<!--    方式一:使用原生的Spring API接口-->
    <!--配置aop,需要导入aop的约束-->
    <aop:config>
        <!--切入点:expression表达式,execution(要执行的位置! * * * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.dakerg.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>


</beans>

测试类

注意此处是接口

public class MyTest {

    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");

        //动态代理代理的是接口:注意点
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();

    }

}

方式二:自定义类来实现【主要是切面的定义】

在上面的基础上添加一个自定义类

public class DiyPointCut {

    public void before(){
        System.out.println("=======方法执行前=========");
    }

    public void after(){
        System.out.println("=======方法执行后=========");
    }

}

配置

<!--方式二:自定义类-->
    <bean id="diy" class="com.dakerg.diy.DiyPointCut"/>

    <aop:config>
        <!--自定义切面 ref要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.dakerg.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现!

自定义类

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//方式三:使用注解方式实现AOP
@Aspect//标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.dakerg.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=====方法执行前====");
    }

    @After("execution(* com.dakerg.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("======方法执行后====");
    }

    //在环绕曾倩中,我恩可以给定一个参数,代表我们要获取切入的点。
    @Around("execution(* com.dakerg.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proceed = jp.proceed();

        System.out.println("环绕后");

    }
    
}

xml配置

 <!--方式三-->
    <bean id="annotationPointCut" class="com.dakerg.diy.AnnotationPointCut"/>
    <!--开始注解支持      JDK(默认,基于接口 proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

十二、整合Mybatis

步骤:

1.导入相关jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关
  • aop织入
  • mybatis-spring【new】

2.编写配置文件

3.测试

<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--Spring操作数据库,还需要一个spring-jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.6</version>
        </dependency>



        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

    </dependencies>

1、回忆MyBatis

1.编写实体类

2.编写核心配置文件

3.编写借口

4.编写Mapper.xml

5.测试

2、Mybatis-Spring

1.编写数据源配置

2.sqlSessionFactory

3.sqlSessionTemplate

spring-dao.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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
        我们这里是用Spring提供的JDBC
    -->
     <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
         <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
         <property name="username" value="root"/>
         <property name="password" value="root"/>
     </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <!--绑定Mabatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>

        <property name="mapperLocations" value="classpath:com/darkerg/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入SqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>


</beans>

4.需要给接口加实现类【】

User实体类

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

UserMapper接口

package com.darkerg.mapper;

import com.darkerg.pojo.User;

import java.util.List;

public interface UserMapper {

    public List<User> selectUser();

}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个队形的Dao/mapper接口-->
<mapper namespace="com.darkerg.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from mybatis.user;
    </select>

</mapper>

新增UserMapper的实现类UserMapperImpl

package com.darkerg.mapper;

import com.darkerg.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper{

    //我们所有的操作,都是用sqlSession来执行,在原来,现在都是使用SqlSessionTemplate。
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

5.将自己写的实现类注入到Spring容器当中

applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">


    <import resource="spring-dao.xml"/>

    <!--专注于注册bean-->
    <bean id="userMapper" class="com.darkerg.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

6.测试使用即可

MyTest

public class MyTest {

    @Test
    public void test1(){

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }

}

3、方式二SqlSessionDaoSupport

试用此种方法只需要在实现类上集成SqlSessionDaoSupport即可

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{

    @Override
    public List<User> selectUser() {

        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();

    }

}

注册bean

<bean id="userMapper2" class="com.darkerg.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

在2中的spring-dao.xml中可免去最后一步sqlSession的配置

十三、声明式事务

1、回顾事务

  • 把一组业务当成一个事务来做,要么都成功,要么都失败!
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎!
  • 确保完整性和一致性。

2、Spring中的事务管理

  • 声明式事务:AOP

    <?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"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            https://www.springframework.org/schema/tx/spring-tx.xsd">
    
        <import resource="spring-dao.xml"/>
    
        <bean id="userMapper" class="com.xiaofan.mapper.UserMapperImpl">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    
        <!-- 配置声明式事务 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <constructor-arg ref="dataSource" />
        </bean>
    
        <!-- 结合aop实现事务的植入-->
        <!-- 配置事务通知 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    
        <!--配置事务切入-->
        <aop:config>
            <aop:pointcut id="txPointCut" expression="execution(* com.xiaofan.mapper.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
        </aop:config>
    </beans>
    
  • 编程式事务:需要在代码中,进行事务的管理。

posted @ 2021-08-18 15:13  DarkerG  阅读(81)  评论(0编辑  收藏  举报