(狂神) Spring 笔记

1.简介

  • Spring:春天----> 给软件行业带来了春天

  • 2002,首次推出了Spring框架的出行:interface21框架

  • Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日正式发布1.0版本

  • Rod Johnson ,Spring Framework创始人,著名作者,很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他不是计算机专业的,而是音乐学。

  • Spring理念:是现有的技术更加容易使用,本身是一个大杂烩。

  • SSH:Struct2 + Spring + Hibernate

  • SSM: SpringMVC + Spring + Mybatis
    官网: https://spring.io/projects/spring-framework#overview

官方下载: https://repo.spring.io/release/org/springframework/spring/

GitHub: https://github.com/spring-projects/spring-framework

依赖:

<!-- 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.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.9</version>
</dependency>

1.2 优点:

  • spring是开源的免费的容器。
  • spring是一个轻量级的,非入侵式的框架。
  • 控制反转(IOC),面向切面编程 (AOP)。
  • 支持事务处理,对框架整合的支持。
    总结:spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。

1.3 组成 七大部件

在这里插入图片描述

2、 IOC 理论推导

2.1 引言:

  • UserDao
  • UserDaoImp
  • UserSevice
  • UserServiceImp

在之前,用户的需求可能会影响原来的代码。
在这里插入图片描述
之前,程序是主动创建对象,控制权在程序员手上。

使用set注入之后,程序不再具有主动性,变成了被动的接收对象。

IOC思想,从本质上解决了问题,程序员不用再去管理对象的创建了,系统的耦合性降低,可以更加专注的业务层
这是IOC的原型,反转就是把主动权交给用户

2.2 控制反转

控制:谁来控制对象的创建,传统应用是由程序员控制对象的创建,使用spring后,对象是由spring来控制
反转:程序本身不创建对象,而变成被动的接收对象
依赖注入:就是利用set方法来进行注入
IOC是一种编程思想,由主动的编程变成被动的接收
可以通过ClassPathXmlApplicationContext 去浏览一下底层源码

现在,我们彻底不用在程序中改动了,要实现不同的操作,只需要在xml配置中进行修改。所谓的IOC:对象由spring进行创建、管理、装配

    <!--ref引用spring中已经创建很好的对象-->
    <!--value是一个具体的值-->

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

    <!--bean = 对象-->
    <!--id = 变量名-->
    <!--class = new的对象-->
    <!--property 相当于给对象中的属性设值-->
</beans>

3. IOC创建对象的方式

3.1 使用无参构造创建对象,默认

3.2 有参构造创建对象有三种方式

3.2.1 下标匹配方式 0 表示下标为0的参数 (也就是第一个参数)

        <bean id="user" class="com.hardy.pojo.User">
            <constructor-arg index="0" value="hardy"/>
        </bean>

3.2.2 参数类型匹配方式,不建议使用,两个string会冲突

        <bean id="user" class="com.hardy.pojo.User">
            <constructor-arg type="java.lang.String" value="hardy"/>
        </bean>

3.2.3 直接通过参数名匹配 ref

        <bean id="user" class="com.hardy.pojo.User">
            <constructor-arg name="name" value="hardy3"/>
        </bean>

3.3 小总结:

在配置文件加载的时候,所有的bean就已经被实例化了,要用直接去get,就可以了
内存中只有一份实例

    public static void main(String[] args) {
    	//绑定完配置文件,bean就已经被实例化了
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        User user = (User) context.getBean("user");
        user.show();
        System.out.println(user);
    }

4. Spring配置

4.1 别名

	<alias name="user" alias="userNew"/>

4.2 bean的配置

    <!--id : bean 的唯一标识符
        class : bean对象所对应的全限定名:包名 + 类名
        name : 也是别名,而且name可以取多个别名
        scope : 作用域   singleton : 单例
    -->
    <bean id="user" class="com.hardy.pojo.User" name="user2,u2" scope="singleton">
    <constructor-arg name="name" value="hardy3"/>
    </bean>

4.3、 import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个

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

5. 依赖注入(DI)dependency injection

5.1 构造器注入

前面讲过了

5.2 set方式注入【重点】

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

【环境搭建】
1.复杂类型

public class Address {

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2.真实测试对象

    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;

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

    <bean id="address" class="com.hardy.pojo.Address">
        <property name="address" value="郑州"/>
    </bean>

    <bean id="student" class="com.hardy.pojo.Student">
        <!-- 第一种,普通值注入  value-->
        <property name="name" value="hardy"/>
        <!-- 第二种,bean注入  ref-->
        <property name="address" ref="address"/>
        <!-- 第三种,数组注入-->
        <property name="books">
            <array>
                <value>三国演义</value>
                <value>水浒传</value>
                <value>红楼梦</value>
                <value>西游记</value>
            </array>
        </property>
        <!-- 第四种,list集合注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>看书</value>
                <value>学Java</value>
            </list>
        </property>
        <!-- 第五种,map注入-->
        <property name="card">
            <map>
                <entry key="校园卡" value="201112084"/>
                <entry key="银行卡" value="2637643487362476376"/>
            </map>
        </property>
        <!-- 第六种,set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>梦幻西游</value>
                <value>绝地求生</value>
            </set>
        </property>
        <!-- 第七种,null值注入-->
        <property name="wife">
            <null/>
        </property>
        <!-- 第八种,Properties 特殊值注入-->
        <property name="info">
            <props>
                <prop key="driver">201112084</prop>
                <prop key="url">hardy</prop>
                <prop key="username">root</prop>
                <prop key="password">root</prop>
            </props>
        </property>
    </bean>
</beans>

4.测试类

public class MyTest {
    public static void main(String[] args) {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

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

        System.out.println(student.toString());
        /**
         * Student{
         *  name='hardy',
         *  address=Address{address='郑州'},
         *  books=[三国演义, 水浒传, 红楼梦, 西游记],
         *  hobbys=[听歌, 看书, 学Java],
         *  card={
         *      校园卡=201112084,
         *      银行卡=263764348736246},
         *  games=[LOL, 梦幻西游, 绝地求生],
         *  wife='null',
         *  info={
         *      password=root,
         *      url=hardy,
         *      driver=201112084,
         *      username=root}}
         */
    }
}

5.3 拓展方式注入

我们可以使用P命名空间 和 C命名空间注入
注:需要导入xml约束

	xmlns:p="http://www.springframework.org/schema/p"
	
    <!--p命名空间注入,可以直接注入属性  property  -->
    <bean id="user" class="com.hardy.pojo.User" p:age="18" p:name="hardy"/>
	xmlns:c="http://www.springframework.org/schema/c"   
	 
	<!--C命名空间注入,通过有参构造器注入,constructor  -->
    <bean id="user2" class="com.hardy.pojo.User" c:name="张三" c:age="23"/>

5.4 bean的作用域:6种

singleton:全局只能有1个
prototype:每一个变量都有一个自己的
request   以下的只能在web中使用
session
application
websocket
5.4.1 单例模式(spring默认机制)
    <!--C命名空间注入,通过有参构造器注入,constructor  -->
    <bean id="user2" class="com.hardy.pojo.User" c:name="张三" c:age="23" scope="singleton"/>
    
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
        User user = (User) context.getBean("user2",User.class);
        User user2 = (User) context.getBean("user2",User.class);
        System.out.println(user==user2);
    }
    //结果为:true
5.4.2 原型模式 每一次从容器中get的时候,会产生新的对象
    <!--C命名空间注入,通过有参构造器注入,constructor  -->
    <bean id="user2" class="com.hardy.pojo.User" c:name="张三" c:age="23" scope="prototype"/>

	@Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
        User user = (User) context.getBean("user2",User.class);
        User user2 = (User) context.getBean("user2",User.class);
        System.out.println(user==user2);
    }
    //结果为:false

6.bean的自动装配

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

在spring中有三种装配方式:

1.在xml中显示的配置
2.在Java中显示的配置
3.隐式的自动装配bean【重要】

6.1 测试

  • 环境搭建
    • 一个人有两只宠物!

7.2 ByName自动装配

        <bean id="cat" class="com.hardy.pojo.Cat"/>
        <bean id="dog222" class="com.hardy.pojo.Dog"/>

        <!--  byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的  bean id
              byType:会自动在容器上下文中查找,和自己对象类型相同的  bean id
              必须保证这个类型全局唯一  不然xml中直接报错
        -->
        <bean id="people" class="com.hardy.pojo.People" autowire="byName">
            <property name="name" value="张三" />
        </bean>

7.3 ByType自动装配

        <bean id="cat" class="com.hardy.pojo.Cat"/>
        <bean id="dog222" class="com.hardy.pojo.Dog"/>
        
        <!--  byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的  bean id
              byType:会自动在容器上下文中查找,和自己对象类型相同的  bean id
              必须保证这个类型全局唯一  不然xml中直接报错
        -->
        <bean id="people" class="com.hardy.pojo.People" autowire="byType">
            <property name="name" value="张三" />
        </bean>

小结:

  • byname:需要保证所有bean的ID唯一,并且这个bean需要和自动注入的属性的set方法的值一致
  • bytype:需要保证所有bean的class唯一,并且这个bean需要和自动注入的类型一致。

7.4 使用注解实现自动装配

使用注解自动装配

jdk1.5支持的注解,spring2.5支持的注解

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

  • 使用注解须知:
    - 1、导入约束:context约束
    - 2、配置注解的支持: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上使用
我们可以不用编写set方法,前提是你自动装配的属性在IOC容器中,且符合名字byname

  • 科普:
@Nullable  字段标记了这个注解,说明这个字段可以为null   
//例如:
    public People(@Nullable String name) {
        this.name = name;
    }
源码:
public @interface Autowired {
    boolean required() default true;
}

@Autowired(required = false)
//说明这个对象可以为null,否则不允许为空,即使为null也不会报错

测试代码:

public class People {
    //说明这个对象可以为null,否则不允许为空,即使为null也不会报错
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候

我们可以使用@Qualifier(value = “dog”)去配合使用,指定一个唯一的id对象

public class People {

    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}

@Resource 注解

public class People {

    @Resource(name = "cat2")
    private Cat cat;
    @Resource
    private Dog dog;
}

小结:

  • @Resource和@Autowired的区别:
    • 都是用来自动装配的,都可以放在属性字段上
    • @Autowired 默认通过byType的方式实现
    • @Resource 默认通过byname的方式实现,如果找不到名字,则通过byType方式实现
    • 执行顺序不同:@Autowired 默认通过byType的方式实现,@Resource 默认通过byname的方式实现

7. 使用注解开发

  • 确定已经导入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"
       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">

    <!--开启注解支持-->
    <context:annotation-config/>
</beans>

1.bean

//@Component 组件
//等价于<bean id="user" class="com.hardy.pojo.User">

@Component
public class User {
    public String name;
}

2.属性如何注入

@Component
public class User {
    
    public String name;
    @Value("hardy")
    //相当于<property name="name" value="hardy"/>
    public void setName(String name) {
        this.name = name;
    }
}

3.衍生的注解

  • @Component 有几个衍生的注解,我们在web开发中,会按照mvc三层架构分层
    • dao 【@Repository】
    • service 【@Service】
    • controller 【@Controller】
      这四个注解功能都是一样的,都是代表将某个类注册到spring容器中,装配bean

4.自动装配置

- @Autowired:自动装配通过类型,名字
  如果autowired不能唯一自动装配上属性,则需要通过
- @Qualifier(value = "xxx")
- @Resource:自动装配通过名字,类型
- @Nullable:字段标记了这个注解,说明这个字段可以为null

5.作用域

@Component
@Scope("prototype")
public class User {

    public String name;
    @Value("hardy")
    //相当于<property name="name" value="hardy"/>
    public void setName(String name) {
        this.name = name;
    }
}

6.小结

  • xml与注解:
    • xml 更加万能,适用于任何场合,维护简单方便
    • 注解 不是自己的类使用不了,维护相对复杂
  • xml与注解的最佳实践:
    • xml用来管理 bean
    • 注解只负责完成属性的注入
    • 生产过程中:唯一需要注意,想让注解生效,就必须开启注解的支持
    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.hardy.dao"/>
    <!--开启注解支持-->
    <context:annotation-config/>

8、 使用Java方式配置Spring

8.1配置类

@Configuration
/**
 * 在一个类上,加上Configuration 这个类就变成了配置类
 * Configuration也会被spring托管,因为他本身就是一个component
  */
@ComponentScan("com.hardy")
@Import(HardyConfig2.class)
public class HardyConfig {

    //注册一个bean  id 就是方法名  class属性  就是方法的返回值
    @Bean
    public User getUser(){
        return new User();
    }
}

8.2 实体类

@Component
public class User {
    private  String name;

    public String getName() {
        return name;
    }
    
    @Value("hardy")
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

8.3 测试类

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig 上下文来获取容器,
        // 通过配置类的class对象加载。
        ApplicationContext context = new AnnotationConfigApplicationContext(HardyConfig.class);
        User user = (User) context.getBean("getUser");//配置类的id名就是方法名
        System.out.println(user.getName());
    }
}

9、代理模式

在这里插入图片描述

9.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();
        contract();
        fare();
    }

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

    //签合同
    public void contract(){
        System.out.println("签租赁合同");
    }

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

4.客户端访问代理

public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //中介
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

代理模式的好处:

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

缺点:

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

9.2 加深理解

在这里插入图片描述

9.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理、基于类的动态代理
    - 基于接口----JDK动态代理
    - 基于类:cglib
    - java字节码实现:javasist 【常用】

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

  • proxy这个类用来动态生成代理对象
  • InvocationHandler用来处理业务
  • 模板
public class ProxyInvocationHandler implements InvocationHandler {
    //与业务接口组合
    private Object Target;
    //set方法 注入业务
    public void setTarget(Object target) {
        Target = target;
    }

    //生成代理类
    //获取当前类的加载器,获取业务的接口,当前对象
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                Target.getClass().getInterfaces(),this);

    }

    //处理业务,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //niubi
        log(method.getName());
        Object result = method.invoke(Target, args);
        return result;
    }

    //添加日志
    public void log(String msg){
        System.out.println("[debug]调用了"+msg+"方法");
    }
}
public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色,不存在,找他的处理程序
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        pih.setTarget(userService);//设置要代理的对象
        //动态生成代理类
        UserService proxy = (UserService) pih.getProxy();

        proxy.delete();
    }
}

动态代理的好处:

  • 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
  • 公共业务交给代理角色,实现业务分工
  • 公共业务发生扩展时,方便集中管理
  • 一个动态代理类代理的一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可

10. AOP

10.1 什么是AOP

aop(aspect oriented programming):面向切面编程。通过预编译的方式和运行期动态代理实现程序功能的统一维护的一种技术。

在这里插入图片描述

10.2 AOP在Spring中的作用

提供声明式事务:允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即:与我们逻辑无关的,但是我们需要专注的部分,就是横切关注点。如:日志,安全,缓存,事务等等
  • 切面(aspect):横切关注点被 模块化 的特殊对象。即:它是一个类
  • 通知(advice):切面必须要完成的工作。即:它是类中的一个方法
  • 目标(target):被通知的对象
  • 代理(proxy):向目标对象应用通知之后创建的对象
  • 切入点(PointCut):切面通知 执行的 “地点” 的定义
  • 连接点(joinPoint):与切入点匹配的执行点

在这里插入图片描述

10.3 使用Spring实现AOP

使用AOP织入,需要导入一个依赖包

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
</dependencies>
10.3.1 方式一:使用spring的API接口

动态代理代理的是接口,静态代理代理的是实体类

  • 1.配置了 前置日志和后置日志
  • 2.准备了UserService和UserServiceImpl实体类 实现了增删改查

配置:

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

    <!--方式一:  使用原生spring API接口    -->
    <!--配置aop-->
    <aop:config>
        <!--切入点   expression:表达式   execution(要执行的位置! *  *  *  * ) 第一个*表示方法类型-->
        <aop:pointcut id="pointcut" expression="execution(* com.hardy.service.UserServiceImpl.*(..))"/>

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

log

public class Log implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(method.getClass().getName()+"类,执行了"+method.getName()+"方法");
    }
}

public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法"+returnValue);
    }
}

测试:

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

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是UserService接口
        UserService userservice = (UserService) context.getBean("userService");

        userservice.query();
    }
}
10.3.2 方式二:使用自定义类实现AOP

自定义log类

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

配置:

    <!--注册bean    -->
    <bean id="userService" class="com.hardy.service.UserServiceImpl"/>

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

    <aop:config>
        <aop:aspect ref="diy">
            <!-- 切入点-->
            <aop:pointcut id="point" expression="execution(* com.hardy.service.UserServiceImpl.*(..))"/>
            <!--  切面 -->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

测试:

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

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是UserService接口
        UserService userservice = (UserService) context.getBean("userService");

        userservice.query();
    }
}
10.3.3 方式三:使用注解实现AOP

自定义一个类充当切面:

//方式三:使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.hardy.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("========方法执行前=========");
    }
    @After("execution(* com.hardy.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("========方法执行后=========");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.hardy.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("========环绕前=========");

        Signature signature = pj.getSignature();//获得签名
        System.out.println("signature:"+signature);//打印调用的方法
        //执行方法
        Object proceed = pj.proceed();

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

配置:

    <!--注册bean    -->
    <bean id="userService" class="com.hardy.service.UserServiceImpl"/>

    <!--方式三:  使用注解实现   -->
    <bean id="annotationPointCut" class="com.hardy.diy.AnnotationPointCut"/>
    <!--开启注解支持    -->
    <aop:aspectj-autoproxy/>

测试:

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

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是UserService接口
        UserService userservice = (UserService) context.getBean("userService");

        userservice.query();
    }
}

结果:环绕在最外层最早和最晚执行,

========环绕前=========
signature:void com.hardy.service.UserService.query()
========方法执行前=========
查询了一条数据
========方法执行后=========
========环绕后=========

11. 整合Mybatis

步骤:

  • 1.导入相关jar包
    • Junit
    • mybatis
    • MySQL
    • spring相关
    • aop织入
    • mybatis-spring 【new】

配置:

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.19.RELEASE</version>
        </dependency>
        <!--spring操作数据库的话,还需要spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
    </dependencies>

maven 资源导出问题

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
  • 2.编写配置文件
  • 3.测试

11.1 回忆Mybatis

1.编写实体类

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

2.编写核心配置文件
mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    
    <typeAliases>
        <package name="com.hardy.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.hardy.mapper.UserMapper"/>
    </mappers>
</configuration>

3.编写接口
UserMapper

public interface UserMapper {
    List<User> selectUser();
}

4.编写Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.hardy.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from mybatis.user;
        </select>
</mapper>

5.测试

    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

注意点:
1.找不到类就是maven资源导出问题 target中没有导出文件
2.编写完mapper.xml文件后,一定要去mybatis-config.xml中绑定mapper
3.数据库UTC设置 Asia/Shanghai
4.工具类放下下面

//sqlSessionFactory -->sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            //使用mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";//注意
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //
    public static SqlSession getSqlSession(){
         return sqlSessionFactory.openSession(true);
    }

}

11.2 Mybatis-spring

1.编写数据源配置
2.sqlSessionFactory
3.sqlSessionTemplete

  • 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:context="http://www.springframework.org/schema/context"
       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/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">

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
        我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource
    -->
    <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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
        <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"/>
        <!--bound mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册usermapper-->
        <property name="mapperLocations" value="classpath:com/hardy/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate,就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--通过构造器给SqlSessionTemplate 传入参数   它需要一个sqlSessionFactory
        且它没有set方法,只能用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

4.给接口添加实现类

//给接口添加实现类
public class UserMapperImpl implements UserMapper{

    //原来我们所有操作都使用sqlsession,现在所有都使用SqlSessionTemplate,他俩一样
    private SqlSessionTemplate sqlSession;

    //spring万物皆注入  一定要来个set方法
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

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

        return  mapper.selectUser();
    }
}

5.将自己写的实现类,注入到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:context="http://www.springframework.org/schema/context"
       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/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">

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

    <!--将实习类 注入到spring中-->
    <bean id="userMapper" class="com.hardy.mapper.UserMapperImpl">
        <!--UserMapperImpl 类中需要SqlSessionTemplate这个参数,传入      -->
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

6.测试

    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = (UserMapper) context.getBean("userMapper");
        for (User user : mapper.selectUser()) {
            System.out.println(user);
        }
    }

方式二 SqlSessionDaoSupport

在这里插入图片描述

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

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
        我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource
    -->
    <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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
        <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"/>
        <!--bound mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册usermapper-->
        <property name="mapperLocations" value="classpath:com/hardy/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate,就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--通过构造器给SqlSessionTemplate 传入参数   它需要一个sqlSessionFactory
        且它没有set方法,只能用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

实现类:UserMapperImpl2

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUser() {
//        SqlSession sqlSession = getSqlSession();
//        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        return mapper.selectUser();
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

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

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

    <!--方式二:将实现类 注入到spring中-->
    <bean id="userMapper2" class="com.hardy.mapper.UserMapperImpl2">
        <!--UserMapperImpl 类中需要SqlSessionTemplate这个参数,传入      -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

测试:

    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = (UserMapper) context.getBean("userMapper2");
        for (User user : mapper.selectUser()) {
            System.out.println(user);
        }
    }

12、声明式事务

12.1 回顾事务

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

事务的ACID原则:

  • 原子性(atomic)
    - 要么都成功,要么都失败
  • 一致性(consistency)
    - 操作前和操作后,数据总量不变
  • 隔离性(isolation)
    - 多个业务操作同一资源,不能互相干扰,防止数据损坏
  • 持久性(durability)
    - 事务一旦提交,不可回滚,无论系统发生什么问题,结果都不受影响,被持久化的写到存储器中。

12.2 spring中的事务管理

增删改需要事务,查询不需要(查询设置为只读)

  • 声明式事务:AOP 【交由容器管理事务】
  • 编程式事务:需要在代码中,进行事务的管理 【需要改变代码】
12.2.1 补充:spring中的七种事务传播属性:propagation 传播

required(依赖):支持当前事务,如果当前没有事务,就新建一个事务 【默认】
supports(支持):支持当前事务,如果当前没有事务,就以非事务的方式执行
mandatory(强制):支持当前事务,如果当前没有事务,就抛出异常
required_new:新建事务,如果当前存在事务,把当前事务挂起
not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
never:以非事务方式执行,如果当前存在事务,则抛出异常
nested(嵌套):支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务
例如:

    <!--结合AOP实现事务的织入-->
    <!--配置事务的类:spring-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:new-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
        </tx:attributes>
    </tx:advice>

真实开发

  <tx:method name="*" propagation="REQUIRED"/>
12.2.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: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">

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
        我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource
    -->
    <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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
        <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"/>
        <!--bound mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册usermapper-->
        <property name="mapperLocations" value="classpath:com/hardy/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate,就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--通过构造器给SqlSessionTemplate 传入参数   它需要一个sqlSessionFactory
        且它没有set方法,只能用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--配置声明式事务  官网的-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--有属性可以用 property 赋值,没有可以用构造器-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--结合AOP实现事务的织入-->
    <!--配置事务的类:spring-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:new-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    
    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.hardy.mapper.*.*(..))"/>
        <!--切入    txAdvice包下的所有方法 都会编织上事务   -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>
12.2.3 思考:为什么需要事务?
  • 如果不配置事务,可能存在数据提交不一致的情况
  • 如果我们不在spring中去配置声明式事务,我们就需要在代码中手动配置事务
  • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题
  • 1
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值