Spring5学习笔记

1.Spring

参考笔记

1.1简介

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

  • 2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。

  • 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。

  • 很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。

Spring理念 : 使现有技术更加容易使用 . 本身就是一个大杂烩 , 整合现有的框架技术

  • SSH: Struts2为控制器(controller) ,spring 为事务层(service), hibernate 负责持久层(dao)
  • SSM: springMVC为控制器(controller) ,spring 为事务层(service), MyBatis 负责持久层(dao)

官网 : http://spring.io/

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

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

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

1.2 优点

  • Spring是一个开源免费的框架 (容器)!

  • Spring是一个轻量级的框架 , 非入侵式的

  • 控制反转 IOC , 面向切面 AOP

  • 对事务的支持 , 对框架整合的支持

总结:Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。

1.3 组成

Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .
Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .

在这里插入图片描述
在这里插入图片描述

核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。

1.4 拓展

在这里插入图片描述

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

2.IOC理论推导

2.1传统实现

  • UserDao 接口
public interface UserDao {
   public void getUser();
}
  • UserDaoImpl 实现类
public class UserDaoImpl implements UserDao {
   @Override
   public void getUser() {
       System.out.println("获取用户数据");
  }
}
  • UserService 业务接口
public interface UserService {
   public void getUser();
}
  • UserServiceImpl 业务实现类
public class UserServiceImpl implements UserService {
   private UserDao userDao = new UserDaoImpl();

   @Override
   public void getUser() {
       userDao.getUser();
  }
}

测试一下

@Test
public void test(){
   UserService service = new UserServiceImpl();
   service.getUser();
}
  • 把Userdao的实现类增加一个 .
public class UserDaoMySqlImpl implements UserDao {
   @Override
   public void getUser() {
       System.out.println("MySql获取用户数据");
  }
}
  • 紧接着我们要去使用MySql的话 , 我们就需要去service实现类里面修改对应的实现
public class UserServiceImpl implements UserService {
   private UserDao userDao = new UserDaoMySqlImpl();

   @Override
   public void getUser() {
       userDao.getUser();
  }
  }

代码量十分大,修改一次的成本十分昂贵!

2.2优化 用set接口

  • 我们使用一个Set接口实现,已经发生了革命性的变化!
public class UserServiceImpl implements UserService {
   private UserDao userDao;
	// 利用set实现
   public void setUserDao(UserDao userDao) {
       this.userDao = userDao;
  }

   @Override
   public void getUser() {
       userDao.getUser();
  }
}

之前,程序是主动创建对象,控制权在程序员手上!
使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象
这种思想,从本质上解决了问题,我们程序员不用再去管对象的创建了。系统的耦合性大大降低,可以专注在业务的实现上!这是IOC的原型

2.3IOC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。

  • 没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
  • 采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

在这里插入图片描述
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

3.HelloSpring

Hello

public class Hello {
    private String str;

    public Hello() {
        this.str = str;
    }

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

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

beans.xml

使用Spring来创建对象 在Spring这些都称为Bean

        类型   变量名 =new 类型();
        Hello hello=new Hello();
        
       id=变量名         class=new的对象
       property 相当于给对象中的属性设置一个值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

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

</beans>

Test

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象都在Spring中管理  要用直接去里面取出来就行
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

4.IOC创建对象的方式

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

  • User
public class User {
    private String name;

    public User() {
        System.out.println("无参构造");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public  void  showName(){
        System.out.println("name="+name);
    }

}

  • 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="user" class="com.wang.pojo.User">
        <property name="name" value="王一一"/>
    </bean>

</beans>
  • Test
public class MyTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User)context.getBean("user");
        user.showName();
    }
}

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

1.下标赋值

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>

2.构造参数类型

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>

3.构造参数名

<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>

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

5.Spring的配置

5.1 别名

在配置文件中添加别名

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

在测试文件中使用别名

 User user = (User)context.getBean("aliuser");
        user.showName();

5.2 bean的配置

bean就是java对象,由Spring创建和管理

  id : bean的标识符,要唯一,如果没有配置id,name就是默认标识符    如果配置id,又配置了name,那么name是别名
 name:可以设置多个别名,比alias更高级可以用 逗号,分号,空格隔开   
 如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;

 class : bean的全限定名=包名+类名

<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
   <property name="name" value="Spring"/>
</bean>

5.3 import

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

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

  • 在总配置文件中:
<import resource="{path}/beans1.xml"/>
<import resource="{path}/beans2.xml"/>
<import resource="{path}/beans3.xml"/>

6.依赖注入

6.1 构造器注入

6.2 set方式注入(重要)

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

6.2.1模拟环境搭建

6.2.2两个实体类

  • 被引用的类(复杂类型)
public class Address {
    private String address;

    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
  • 主体的类(真实的测试对象) 属性加get set
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;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

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

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

6.2.3配置 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.wang.pojo.Address"/>

    <bean name="student" class="com.wang.pojo.Student">
        <!--    第一种:普通值注入,value-->
        <property name="name" value="王一一"/>
        <!--    第二种: bean注入  ref是表的是引用这个对象,相当于是传入这个对象的引用-->
        <property name="address" ref="address"/>
        <!--        第三种:数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
            </array>
        </property>
        <!--        第四种:list注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>看书</value>
                <value>跑步</value>
            </list>
        </property>
        <!--        第五种:map注入-->
        <property name="card">
            <map>
                <entry key="编号" value="999"/>
                <entry key="年纪" value="33"/>
            </map>
        </property>
        <!--Set-->
        <property name="games">
            <set>
                <value>CF</value>
                <value>LOL</value>
                <value>GTA</value>
            </set>
        </property>

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

        <!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">20190526</prop>
                <prop key="username">root</prop>
                <prop key="password">root</prop>
            </props>
        </property>


    </bean>
   
</beans>

6.2.4测试

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);
    }
}

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

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

    <!--c命名空间注入,通过构造器注入:construt-args-->
    <bean id="user2" class="com.kuang.pojo.User" c:name="狂神2" c:age="11"/>

</beans>

注意点:p命名和c命名空间不能直接使用,需要导入xml约束!

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

6.4 bean的作用域

在这里插入图片描述
单例模式(Spring默认机制)

  • user1==user2
<bean id="user2" class="com.kuang.pojo.User" c:name="狂神2" c:age="11" scope="singleton"/>

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

  • user1!=user2
<bean id="user2" class="com.kuang.pojo.User" c:name="狂神2" c:age="11" scope="prototype"/>

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

7.bean的自动装配

  • 自动装配是Spring满足bean依赖的一种方式

  • Spring会在上下文中自动寻找,并自动给bean装配属性

  • 在Spring中有三种装配的方式

    • 在xml中显示的配置
    • 在java中显示的配置
    • 隐式的自动装配bean 【重要】

7.1 测试

环境搭建:一个人有两个宠物

<?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="cat" class="com.wang.pojo.Cat"/>
    <bean id="dog" class="com.wang.pojo.Dog"/>
    <bean id="people" class="com.wang.pojo.People">
        <property name="name" value="王"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>


</beans>

7.2 byName自动装配

<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>

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

7.3 byTpye自动装配

	<!--
        byName : 会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean_id
        byType : 会自动在容器上下文中查找,和自己对象属性类型相同的bean
    -->
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
    <property name="name" value="狂神"/>
</bean>

小结:

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

7.4 使用注解实现自动装配

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

  • 要使用注解须知
  1. 导入约束:context约束
xmlns:context="http://www.springframework.org/schema/context"
  1. 配置注解的支持 <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;
}

测试代码:

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

当@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候:
使用** @Qualifier(value = “xxx”) **去配合@Autowire的使用,指定一个唯一的bean对象注入!

public class People {

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

@Resource

public class People {

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

小结:

  • @Resource和@Autowired的区别:

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

8 Spring注解开发

在Spring4之后,要使用注解开发,必须保证AOP的包导入了
在这里插入图片描述
使用注解需要导入context约束,增加注解的支持

8.1.bean

import org.springframework.stereotype.Component;
//等价于 <bean id="user" class="com.wang.pojo.User"/>
//@Component 组件
@Component
public class User {
    public String name="秦疆";
}

8.2.属性如何注入@Component @Value

//等价于 <bean id="user" class="com.wang.pojo.User"/>
//@Component 组件
@Component
public class User {
    //相当于<property name="name" value="王"></property>
    @Value("王")
    public String name;

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

8.3.@Component衍生的注解

@Component的衍生注解,在web开发中会用到,按照mvc三层架构分层

  • Dao
@Repository
public class UserDao {
}
  • Service
@Service
public class UserService {
}

  • Controller
@Controller
public class UserController {
}

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

8.4.自动装配装置

  • @Resource 自动装配通过名字 类型
  • @Autowired 自动装配通过类型
    • 环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候:
      使用** @Qualifier(value = “xxx”) **
  • @Nullable 字段标记了这个注解,说明这个字段可以为null

8.5.作用域

例如:单例模式

@Scope("singleton")  // <bean scope="singleton"/>

//等价于 <bean id="user" class="com.wang.pojo.User"/>
//@Component 组件
@Component
@Scope("singleton")  // <bean scope="singleton"/>
public class User {
    //相当于<property name="name" value="王"></property>
    @Value("王")
    public String name;

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

8.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:annotation-config/>
    <!--指定要扫描的包-->
    <context:component-scan base-package="com.pojo"/>

</beans>

9.使用java方式配置spring

JavaConfig

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

实体类

@Component
public class User {

    @Value("dong")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

配置文件

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


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

}

测试类

如果完全使用了配置类的方式取做,只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载

public class MyTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User)context.getBean("getUser");
        System.out.println(user.getName());
    }
}

这种纯java配置方式

在springboot中,随处可见

10.静态代理和动态代理

我的设计模式笔记

11.AOP

11.1什么是aop

  • aop:(aspect Orientend Programming)意为:面向切面编程

11.2Aop在spring中的作用

  • 提供声明式事物:允许用户自定义切面
    在这里插入图片描述

需要了解名词:

  • 横切关注点:跨越应用想程序多个模块的方法或共功能。既是,与我们的业务逻辑无关,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等。。。。

  • 切面(Aspect):横切关注点被模块化的特殊对象。即是,它是一个类。

  • 通知(Advice):切面必须完成的工作。即,它是类中的一个方法。

  • 目标(Target):被通知的对象。

  • 代理(Proxy):向目标对象应用通知之后创建的对象。

  • 切入点(PointCut):切面通知执行的“地点”的定义

  • 连接点(Join Point):与切入点匹配的执行点。

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

在这里插入图片描述

即Aop在不改变原有代码的情况下,去增加新的功能

11.3 使用Spring实现Aop

【重点】使用AOP织入,需要导入一个依赖包!

  • 在pox.xml中加入
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

11.3.1 第一种方式:通过 Spring API 实现AOP

搭建环境:编写业务接口和实现类

public interface UserService {
 
    public void add();
 
    public void delete();
 
    public void update();
 
    public void search();
 
}
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 search() {
        System.out.println("查询用户");
    }
}
编写两个增强类 , 一个前置增强 一个后置增强
public class Log implements MethodBeforeAdvice {
 
    //method : 要执行的目标对象的方法
    //objects : 被调用的方法的参数
    //Object : 目标对象
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
    }


public class AfterLog implements AfterReturningAdvice {
    //returnValue 返回值
    //method被调用的方法
    //args 被调用的方法的对象的参数
    //target 被调用的目标对象
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了" + target.getClass().getName()
        +"的"+method.getName()+"方法,"
        +"返回值:"+returnValue);
    }
}
去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: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.wang.log.userService"/>
    <bean id="log" class="com.wang.log.log"/>
    <bean id="afterLog" class="com.wang.log.AfterLog"/>
 
    <!--aop的配置-->
    <aop:config>
        <!--切入点  expression:表达式匹配要执行的方法-->
        <aop:pointcut id="pointcut" expression="execution(* com.wang.service.UserServiceImpl.*(..))"/>
        <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
        <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 test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.search();
    }
}

Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .

Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 .
实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理

11.3.2 第二种方式:使用自定义类实现AOP

主要是切面
目标业务类不变依旧是userServiceImpl

写我们自己的一个切入类
public class DiyPointcut {
 
    public void before(){
        System.out.println("---------方法执行前---------");
    }
    public void after(){
        System.out.println("---------方法执行后---------");
    }
    
}
去spring中配置
<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="diy" class="com.kuang.config.DiyPointcut"/>
 
<!--aop的配置-->
<aop:config>
    <!--第二种方式:使用AOP的标签实现-->
    <aop:aspect ref="diy">
        <aop:pointcut id="diyPonitcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
        <aop:before pointcut-ref="diyPonitcut" method="before"/>
        <aop:after pointcut-ref="diyPonitcut" method="after"/>
    </aop:aspect>
</aop:config>
测试:
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }

11.3.3 第三种方式:使用注解实现AOP

使用注解实现AOP

第一步:编写一个注解实现的增强类

package com.kuang.config;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//标注这个类是一个切面 
@Aspect
public class AnnotationPointcut {
   //方法执行前
    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("---------方法执行前---------");
    }
 	//方法执行后
    @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("---------方法执行后---------");
    }
 
    @Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("签名:"+jp.getSignature());
        //执行目标方法proceed
        Object proceed = jp.proceed();
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}

第二步:在Spring配置文件中,注册bean,并增加支持注解的配置

<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.kuang.config.AnnotationPointcut"/>
//开启注解支持
<aop:aspectj-autoproxy/>

aop:aspectj-autoproxy:说明

通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了
 
<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

12 整合Mybatis

步骤

  • 导入相关的依赖

  • 编写配置文件

  • 测试

导入的依赖:

  • junit
  • mysql数据库
  • mybatis
  • spring-webmvc:spring相关的
  • spring-jdbc :Spring操作数据库的话,还需要导入spring-jdbc
  • aspectjweaver:aop织入
  • mybatis-spring重要!!新知识
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springstudy02</artifactId>
        <groupId>com.wang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-10-mybatis</artifactId>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
    </dependencies>

</project>

12.1 回忆mybatis

1.编写实体类

package com.kuang.pojo;
 
public class User {
    private int id;  //id
    private String name;   //姓名
    private String pwd;   //密码
}

2.实现mybatis的配置文件

<?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>
 
    <typeAliases>
        <package name="com.kuang.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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
 
    <mappers>
        <package name="com.kuang.dao"/>
    </mappers>
</configuration>

3.编写接口
UserDao接口编写

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

4.编写相应接口的Mapper.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">
<mapper namespace="com.kuang.dao.UserMapper">
 
    <select id="selectUser" resultType="User">
      select * from user
    </select>
 
</mapper>

5.测试

@Test
public void selectUser() throws IOException {
 
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
 
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
 
    List<User> userList = mapper.selectUser();
    for (User user: userList){
        System.out.println(user);
    }
 
    sqlSession.close();
}
 

12.2 整合mybatis和spring

引入Spring之前需要了解mybatis-spring包中的一些重要类;

http://www.mybatis.org/spring/zh/index.html

什么是 MyBatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。

知识基础

在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。这很重要

MyBatis-Spring 需要以下版本:

MyBatis-SpringMyBatisSpring 框架Spring BatchJava
2.03.5+5.0+4.0+Java 8+
1.33.4+3.2.2+2.1+Java 6+

如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>
 

要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类即DataSource。

在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:

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

注意:

  1. SqlSessionFactory需要一个 DataSource(数据源)。这可以是任意的 DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
  2. 在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建
  3. **在 MyBatis 中,你可以使用 SqlSessionFactory 来创建 SqlSession。**一旦你获得一个 session 之后,你可以使用它来执行映射了的语句,提交或回滚连接,最后,当不再需要它的时候,你可以关闭 session。
  4. **SqlSessionFactory有一个唯一的必要属性:用于 JDBC 的 DataSource。**这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。
  5. 一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是 < settings> 或 < typeAliases>元素。
  6. **需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。**确切地说,任何环境配置(),数据源()和 MyBatis 的事务管理器()都会被忽略。SqlSessionFactoryBean 会创建它自有的 MyBatis 环境配置(Environment),并按要求设置自定义环境的值。
  7. SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession。
  8. 模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。
  9. 可以使用 SqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。

步骤:

我们需要将spring和mybatis进行整合,首先考虑 mybatis做了什么:mybaits通过读取配置文件的信息,然后生成sqlSessionFactory ,进一步生成sqlsession,然后进行操作。

新建一个spring xml文件
这段代码相当于之前的mybaits-confi 中数据库信息
 <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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
 
    </bean>
 
这段代码相当于配置好sqlsessionFactory,
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定mybatis配置文件-->
        <property name="configuration" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/kuang/mapper/*.xml"/>
    </bean>
如何生成sqlsession呢,我们需要在spring中进行配置。
 <!--就是我们使用的sqlsession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入,因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
 

在之前的mybatis中,我们的sqlsession是通过在实现类生成sqlsession来执行的,那么在spring中,我们是通过注入进行的。

在具体的实现类中,我们生成set方法,以便spring进行注入。
package com.kuang.mapper;
 
import com.kuang.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
 
import java.util.List;
 
public class UserMapperImpl implements UserMapper{
 
    //我们所有的操作,在原来我们的操作都使用sqlsession来执行,现在我们使用sqlsessionTemplate进行
    private SqlSessionTemplate sqlSessionTemplate;
    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSessionTemplate=sqlSession;
    }
    @Override
    public List<User> selectUser() {
        UserMapper mapper=sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}
在xml中进行注册
<bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
 
</bean>
具体的步骤:

1 编写数据源配置

2 sqlSessionFactory

3 sqlSessionTemplate

4 需要给接口加实现类

5 将自己写的实现类,注入到Spring中

6 测试使用即可

SqlSessionTemplate是mybatis-Spring 的核心。作为SqlSession的一个实现,这意味着可以使用它无缝代替代码中已经存在使用的SqlSession ,SqlSessionTemplate是线程安全的。可以被多个DAO映射器使用。

12.3 另一种整合方式

mybatis-spring1.2.3版以上的才有这个 .

官方文档截图 :
dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看

在这里插入图片描述

测试:

测试:

1、将我们上面写的UserDaoImpl修改一下

public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

2、修改bean的配置

<bean id="userDao" class="com.kuang.dao.UserDaoImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

3、测试

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserMapper mapper = (UserMapper) context.getBean("userDao");
    List<User> user = mapper.selectUser();
    System.out.println(user);
}

总结 : 整合到spring以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现,这个等我们后面学习SpringBoot的时候还会测试整合

13 声明式事务

spring中的事务管理:
声明式事务:AOP
编程式事务:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值