Spring笔记

1. Spring

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

1.1 简介

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

官网:https://spring.io/

官方下载地址:https://repo.spring.io/libs-release-local/org/springframework/spring/

maven:

​ webmvc

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.8</version>
</dependency>

​ jdbc

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

1.2 优点

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

1.3 组成

img

  • AOP
  • ORM
  • DAO
  • Web
  • Context
  • Web MVC
  • Core

1.4 拓展

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

  • SpringBoot
    • 一个快速开发的脚手架
    • 基于SpringBoot可以快速的开发单个微服务
    • 约定大于配置
  • Spring Cloud
    • Spring Cloud是基于SpringBoot实现的

现在大多数公司都是使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring和SpringMVC,两者在这起承上启下的作用

  • 弊端:发展太久之后,配置繁琐,人称**“配置地狱”**!

2. IOC

2.1 理论推导

1.UserDao业务接口

2.UserDaoImpl业务实现类

1.UserService业务接口

2.UserServiceImpl业务实现类

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

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

private UserDao userDao;

//利用set动态实现值的注入
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}
  • 之前是程序主动创建对象!控制权在程序员手上!
  • 使用了set注入后,程序不再拥有主动性,而是变成了被动的接受对象!

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

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

2.2 IOC的本质

**控制反转(IOC Inversion of Control)是一种设计思想,DI(依赖注入)是实现IOC的一种方法,**也有人认为DI只是IOC的另外一种说法,没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建交给第三方,获得依赖对象的方式反转了!

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

2.3 HelloSpring

2.4 IOC创建对象的方式

1.使用无参构造创建对象(默认)

2.假设要使用有参构造创建对象

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

3. Spring配置

3.1 别名

    <!--配置别名后可别名和原名称均可访问-->
    <alias name="user" alias="userNew"/>

3.2 Bean的配置

<!--
id:bean的唯一标识符,相当于对象名
class:bean对象所对应的权限定名: 包名 + 类名
name:也是别名,而且name可以同时取多个别名
-->
<bean id="userT" class="com.hao.pojo.UserT" name="user2 u2,u3;u4">
    <property name="name" value="郝建潮T"/>
</bean>

3.3 import

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

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

- 张三
- 李四
- 王五
- applicationContext.xml

使用的时候,直接导入总的就行

4. Di依赖注入

4.1 构造器注入

construct- arg(前边已经讲过)

4.2 Set方式注入[重点]

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

【环境搭建】

复杂类型

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
  • 真实测试对象

    public class Student {
    
        private String name;
        private String address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    }
    
  • 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
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="student" class="com.hao.pojo.Student">
    
            <!--第一种,普通值注入,value-->
            <property name="name" value="haojianchao"/>
    
        </bean>
    
    </beans>
    
  • 测试类

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    
            Student student = (Student) context.getBean("student");
    
            System.out.println(student.getName());
        }
    }
    
  • 完善注入信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.hao.pojo.Address">
        <property name="address" value="陕西"/>
    </bean>


    <bean id="student" class="com.hao.pojo.Student">
        <!--普通值注入,value-->
        <property name="name" value="haojianchao"/>

        <!--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>看P站</value>
                <value>打游戏</value>
            </list>
        </property>

        <!--Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="123123123112311231"/>
                <entry key="银行卡号" value="18281240312312317"/>
            </map>
        </property>

        <!--Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>KIK</value>
                <value>JUJ</value>
            </set>
        </property>

        <!--Null-->
        <property name="wife">
            <null/>
        </property>

        <property name="info">
            <props>
                <prop key="学号">1828124037</prop>
                <prop key="性别"></prop>
                <prop key="username">小郝</prop>
                <prop key="password">20000310</prop>

            </props>
        </property>
    </bean>

</beans>

4.3 拓展方式注入

我们可以使用P命名空间和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
       http://www.springframework.org/schema/beans/spring-beans.xsd">


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

   <!--C命名空间,通过构造器注入:construct-args-->
   <bean id="user2" class="com.hao.pojo.User" c:name="郝建潮" c:age="19"/>

</beans>

测试!

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);

}

注意:

p命名和c命名注入不能直接使用,需要导入xml约束

5. Bean

5.1 Bean的作用域

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

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

<bean id="user2" class="com.hao.pojo.User" c:name="郝建潮" c:age="19" scope="singleton"/>

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

<bean id="user2" class="com.hao.pojo.User" c:name="郝建潮" c:age="18" scope="prototype"/>

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

5.2 Bean的自动装配

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

在Spring中有三种自动装配的方式

​ 1、在xml中显式的配置

​ 2、在java中显示配置

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

测试

  • 环境搭建

    • 一个人有两个宠物
    <bean id="cat" class="com.hao.pojo.Cat"/>
    <bean id="dog" class="com.hao.pojo.Dog"/>
    
    <!--
        byName:会自动在容器上下文中查找和自己对象set方法后边的值对应的beanid!
        byType:会自动在容器上下文中查找和自己对象属性类型相同的bean!
    -->
    <bean id="people" class="com.hao.pojo.People" autowire="byType">
        <property name="name" value="郝大炮啊~"/>
    </bean>
    

小结:

- byname需要保证所有的bean的id唯一,并且这个bean需要和自动注入的set方法后的值一致!
- bytype需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的值一致!

5.3 使用注解实现自动装配

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

要使用注解须知:

​ 1.导入约束

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

    <context:annotation-config/>
    
</beans>

@Autowired

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

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

科普:

@Nullable	//字段标记了这个注解,说明这个字段可以为空

测试代码:

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

如果自动装配的环境比较复杂,自动装配无法通过一个【@Autowired】完成得时候,我们可以使用【@Qualifier】(value = “xxx”)来配合@Autowired来使用,来确保只有一个bean对象注入

public class People {
    @Autowired
    @Qualifier(value = "dog22")
    private Dog dog;
    @Autowired
    @Qualifier(value = "cat222")
    private Cat cat;

    private String name;
}

@Resource

public class People {
    @Resource(name = "dog222")
    private Dog dog;
    @Resource
    private Cat cat;

    private String name;

小结:

​ @Resource和@Autowired的区别:

  • 相同
    都是自动装配的
    - 都可以放在属性字段上
  • 不同点
    • @Autowired通过byType的方式实现,而且必须要求这个对象存在【常用】
    • @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!若两个都找不到,就报错
    • 执行顺序不同

6. 使用注解开发

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

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

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

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

1.bean

2.属性如何注入

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

    public String name;

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

3.衍生的注解

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

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

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

4.自动装配置

- @Autowired  
    自动装配(通过类型 名字)  
    如果不能唯一自动装配上属性,则需要通过@Qualifier(value = "xxx")    
- @Nullable  
    字段标记了这个注解,说明这个字段可以为null
- @Resource  
    自动装配(通过名字 类型)
- @Component  
    组件,放在类上,说明这个类被Spring管理了,就是bean!

5.作用域

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

    public String name;

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

6.小结

​ xml与注解:

	- xml更加万能,适用于任何场合,维护简单方便
	- 注解只是绑定在一个类上的,其余的类使用不了,维护相对复杂!
	- 最佳实践:xml用来管理bean,注解只负责完成属性的注入
	- 在使用的过程中只需要注意:必须让注解生效,就需要开启注解的支持

7. 使用Java的方式配置Spring

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

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

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

实体类User

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

    public String getName() {
        return name;
    }

    @Value("郝建潮")
    public void setName(String name) {
        this.name = name;
    }

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

配置文件MyConfig

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

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

测试类MyTest

public class MyTest {

    public static void main(String[] args) {

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

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

        System.out.println(getUser.getName());
    }
}

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

8. 代理模式

中介:

为什么要学习代理模式?因为是SpringAOP的底层【SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

8.1 静态代理

角色分析:

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

代码步骤:

​ 1.接口

public interface Rent {
    public void rent();

}

​ 2.真实角色

//房东
public class Host implements Rent{
    public void rent(){
        System.out.println("房东要租房子!");
    }
}

​ 3.代理角色

public class Proxy implements Rent {

    private Host host;

    public Proxy(){}

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

    public void rent() {
        seeHouse();
        host.rent();
        hetong();
        fare();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带你看房!");
    }
    //签租赁合同
    public void hetong(){
        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();
    }
}

代理模式的好处:

- 可以使真实角色的操作更加纯粹,无需关注其他公共业务
- 公共业务交给代理角色!实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!

缺点:

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

8.2 静态代理加深理解

聊聊AOP

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

代码步骤:

接口:

//CRUD
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();

}

真实角色:

//真实对象
public class UserServiceImpl  implements UserService{
    public void add() {
        System.out.println("增!");
    }

    public void delete() {
        System.out.println("删!");

    }

    public void update() {
        System.out.println("改!");

    }

    public void select() {
        System.out.println("查!");

    }
}

代理角色:

public class UserServiceProxy implements UserService{

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private UserService userService;

    public void add() {
        log("add");
        userService.add();
    }

    public void delete() {
        log("delete");
        userService.delete();
    }

    public void update() {
        log("update");
        userService.update();
    }

    public void select() {
        log("select");
        userService.select();
    }


    //日志方法
    public void log(String msg){
        System.out.println("[debug]使用了"+msg+"方法");
    }
}

客户端访问代理角色:

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();

        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);
        proxy.add();
    }
}
  • 改动原有业务代码是大忌
  • 开闭原则(对扩展开启,对修改关闭)

8.3 动态代理

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

需要了解两个类:Proxy:代理, InvocationHandler

动态代理的好处:

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

动态代理工具类

//用这个类自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {

    // 被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

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

    //处理代理实例并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //要执行的方法
        //动态代理的本质,就是使用反射机制来实现
        Object result = method.invoke(target, args);
        return result;
    }
}

9. AOP(Aspect Orirnted Programming)

面向切面编程

9.1 什么是AOP?

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

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

9.2 AOP在Spring中的作用

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

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

SpringAOP中,通过Advice定义横切逻辑,Spring中支持五种类型的Advice:

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

9.3 使用Spring实现AOP

[重点]使用AOP需要导入一个依赖包

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>

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

log类

public class Log implements MethodBeforeAdvice {

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

    }
}

afterlog类

public class AfterLog implements AfterReturningAdvice {

    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {

        System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
    }
}

配置文件

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

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

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

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

</beans>

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService = context.getBean("userService", UserService.class);

        userService.select();
    }
}

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

自定义类

public class DiyPointCut {

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

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

配置文件

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

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

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

</beans>

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService = context.getBean("userService", UserService.class);

        userService.select();
    }
}

方式三:使用注解实现

AnnotationPointCut类

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

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

    @After("execution(* com.hao.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=============方法执行后===========");
    }
    
    //扩展
    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.hao.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("环绕前");
        //执行方法
        Object proceed = jp.proceed();
        System.out.println("环绕后");
    }
}

配置文件

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

    <!--注册bean-->
    <bean id="userService" class="com.hao.service.UserServiceImpl"/>
    <bean id="log" class="com.hao.log.Log"/>
    <bean id="afterLog" class="com.hao.log.AfterLog"/>
    
    <!--方式三-->
    <bean id="annotationPointCut" class="com.hao.diy.AnnotationPointCut"/>
    <!--开通注解支持! JDK(proxy-target-class="false") cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy/>

</beans>

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService = context.getBean("userService", UserService.class);
        userService.select();
    }
}

10. 整合Mybatis

步骤:

  • 导入相关jar包
    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aop植入
    • mybatis-spring
  • 编写配置文件
  • 测试

10.1 回忆Mybatis

1.编写实体类

@Data		//@Data注解,提高代码的简洁,可以省去代码中大量的get()、 set()、 toString()等方法;
public class User {
    private int id;
    private String name;
    private String pwd;
}

2.编写核心配置文件

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

<configuration>

    <typeAliases>
        <package name="com.hao.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&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.hao.mapper.UserMapper"/>
    </mappers>

</configuration>

3.编写接口

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

4.编写Mapper.xml

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

</mapper>

5.编写测试文件

public class MyTest {

    @Test
    public void Test() throws IOException {
        String resources = "mybatis-config.xml";
        InputStream input = Resources.getResourceAsStream(resources);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(input);
        SqlSession sqlSession = sessionFactory.openSession(true);
        
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList = mapper.selectUser();

        for (User user : userList) {
            System.out.println(user);
        }
        
        sqlSession.close();
    }
}

10.2 Mybatis-Spring

1.编写数据源配置

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

2.sqlSessionFactory

<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>

    <!--绑定Mybatis配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/hao/mapper/UserMapper.xml"/>
</bean>

3.sqlSessionTemplate

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

4.需要给接口加实现类

public class UserMapperImpl implements UserMapper{

    //我们的所有操作,以往都使用sqlSession来执行,现在都使用sqlSessionTemplate
    private SqlSessionTemplate sqlSession;
    
    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSession = sqlSession;
    }
    
    public List<User> selectUser(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

5.测试()

public class MyTest {

    @Test
    public void Test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");

        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }

    }
}

11. 声明式事务

11.1 回顾事务

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

事务ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中

11.2 Spring的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中进行事务的管理

思考:

为什么需要事务:

  • 如果不配置事务,可能存在数据不一致的情况
  • 如果我们不在Spring中配置声明式事务,就需要在代码中手动配置事务
  • 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值