重学Spring5

1. Spring

1.1 简介

  • Spring : 春天
  • 2002年,首次推出Spring框架的雏形 : interface21框架
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.12.RELEASE</version>
</dependency>

1.2 优点

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

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

1.3 组成

这里写图片描述

组成Spring框架的每个模块(或者组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

  • 核心容器:核心容器提供 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 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务;
  • Spring Cloud是基于Spring Boot实现的;
  • Spring Boot专注于快速、方便集成的单个微服务个体,Spring Cloud关注全局的服务治理框架;
  • Spring Boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot来实现,Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
  • SpringBoot在SpringClound中起到了承上启下的作用,如果你要学习SpringCloud必须要学习SpringBoot。

2. IOC理论推导

新建一个空白的maven项目

我们用我们原先的方式写一段代码 :

  1. 先写一个UserDao接口
public interface UserDao{
    public void getUser();
}
  1. 再去写Dao的实现类
public class UserDaoImpl implements UserDao{
    @Override
    public void getUser(){
        syso("获取用户数据!");
    }
}

3、然后去写UserService的接口

public interface UserService { 
    public void getUser();
}

4、最后写Service的实现类

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override   
    public void getUser() {
        userDao.getUser();  
    }
}

5、测试一下

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

在假设, 我们再增加一个Userdao的实现类 .

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

那么我们要使用Oracle , 又需要去service实现类里面修改对应的实现 . 假设我们的这种需求非常大 , 这种方式就根本不适用了, 甚至反人类对吧 , 每次变动 , 都需要修改大量代码 . 这种设计的耦合性太高了, 牵一发而动全身 .

那我们如何去解决呢 ?

我们可以在需要用到他的地方 , 不去实现它 , 而是留出一个接口 , 利用set , 我们去代码里修改下 .

public class UserServiceImpl implements UserService {   
    private UserDao userDao;
    // 利用set实现   
    public void setUserDao(UserDao userDao) {       
        this.userDao = userDao;  
    }   
    @Override   public void getUser() {       
        userDao.getUser();  
    }
}

现在去我们的测试类里 , 进行测试 ;

@Test
public void test(){   
    UserServiceImpl service = new UserServiceImpl();   
    service.setUserDao( new UserDaoMySqlImpl() );   
    service.getUser();   //那我们现在又想用Oracle去实现呢   
    service.setUserDao( new UserDaoOracleImpl() );   
    service.getUser();
}

大家发现了区别没有 ? 可能很多人说没啥区别 . 但是同学们 , 他们已经发生了根本性的变化 , 很多地方都不一样了 . 仔细去思考一下 , 以前所有东西都是由程序去进行控制创建 , 而现在是由我们自行控制创建对象 , 把主动权交给了调用者 . 程序不用去管怎么创建,怎么实现了 . 它只负责提供一个接口 .

这种思想 , 从本质上解决了问题 , 我们程序员不再去管理对象的创建了 , 更多的去关注业务的实现 . 耦合性大大降低 . 这也就是IOC的原型 !

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

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

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

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

3. IOC本质

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

图片

IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

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

4. Hello Spring

  1. 导入jar包(使用maven,文章一开始有教程)
  2. 编写一个Hello实体类
public class Hello {
   private String name;

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

   public void show(){
       System.out.println("Hello,"+ name );
  }
}

  1. 编写我们的Spring文件,我们命名未beans.xml(为了方便,官方名字叫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就是java对象 , 由Spring创建和管理-->
   <bean id="hello" class="com.dualseason.pojo.Hello">
       <property name="name" value="Spring"/>
   </bean>

</beans>

  1. 我们就可以去测试了
@Test
public void test(){
    //解析beans.xml文件,生成管理相应的Bean对象
    Application context = new ClassPathXmlApplicationContext("beans.xml");
    //getBean : 参数即为Spring配置文件中bean的id
    Hello hello = (Hello)context.getBean("hello");
	hello.show();
}

  1. 思考 :
  • Hello对象是谁创建的?

    • hello对象是有Spring创建的
  • Hello对象的属性是怎么设置的?

    • Hello对象的属性是由Spring容器设置的
  • 这个过程就叫做控制反转

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

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

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

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

可以通过new ClassPathXmlApplicationContext去浏览一下底层代码。

//step1
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
    this(new String[] {configLocation}, true, null);
}
//step2
public ClassPathXmlApplicationContext(
    String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
    throws BeansException {

    super(parent);
    setConfigLocations(configLocations);
    if (refresh) {
        refresh();
    }
}
//step3.1
public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
    super(parent);
}
//step3.2
public void setConfigLocations(@Nullable String... locations) {
    if (locations != null) {
        Assert.noNullElements(locations, "Config locations must not be null");
        this.configLocations = new String[locations.length];
        for (int i = 0; i < locations.length; i++) {
            this.configLocations[i] = resolvePath(locations[i]).trim();
        }
    }
    else {
        this.configLocations = null;
    }
}
//step3.3
@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        prepareRefresh();

        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // Prepare the bean factory for use in this context.
        prepareBeanFactory(beanFactory);

        try {
            // Allows post-processing of the bean factory in context subclasses.
            postProcessBeanFactory(beanFactory);

            // Invoke factory processors registered as beans in the context.
            invokeBeanFactoryPostProcessors(beanFactory);

            // Register bean processors that intercept bean creation.
            registerBeanPostProcessors(beanFactory);

            // Initialize message source for this context.
            initMessageSource();

            // Initialize event multicaster for this context.
            initApplicationEventMulticaster();

            // Initialize other special beans in specific context subclasses.
            onRefresh();

            // Check for listener beans and register them.
            registerListeners();

            // Instantiate all remaining (non-lazy-init) singletons.
            finishBeanFactoryInitialization(beanFactory);

            // Last step: publish corresponding event.
            finishRefresh();
        }

        catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
            }

            // Destroy already created singletons to avoid dangling resources.
            destroyBeans();

            // Reset 'active' flag.
            cancelRefresh(ex);

            // Propagate exception to caller.
            throw ex;
        }

        finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
            resetCommonCaches();
        }
    }
}

  1. 修改案例

我们在上面一开始的的案例中,新增一个Spring配置文件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="MysqlImpl" class="com.dualseason.dao.impl.UserDaoMySqlImpl"/>
   <bean id="OracleImpl" class="com.dualseason.dao.impl.UserDaoOracleImpl"/>

   <bean id="ServiceImpl" class="com.dualseason.service.impl.UserServiceImpl">
       <!--注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写-->
       <!--引用另外一个bean , 不是用value 而是用 ref-->
       <property name="userDao" ref="OracleImpl"/>
   </bean>

</beans>

测试

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
    serviceImpl.getUser();
}

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

5.IOC创建对象方式

  1. 通过无参构造方法来创建

    User.java

public class User{
    private String name;
    public User(){
        syso("user无参构造方法");
    }
    public void setName(String name){
        this.name = name;
    }
    public void show(){
        syso("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.dualseason.pojo.User">
        <property name="name" value="世杰"/>
    </bean>

</beans>

测试

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    //在执行getBean的时候, user已经创建好了 , 通过无参构造
    User user = (User) context.getBean("user");
    //调用对象的方法 .
    user.show();
}

结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了

2.通过有参构造方法来创建

UserT.java

public class UserT {
    private String name;
    public UserT(String name) {
        this.name = name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name="+ name );
    }
}

beans.xml有三种方式编写

<!--第一种根据index参数下标设置-->
<bean id="userT" class="com.dualseason.pojo.UserT">
	<!--index指构造方法,下标从0开始-->
    <constructor-arg index="0" value="世杰"/>
</bean>

<!--第二种根据参数名字设置-->
<bean id="userT" class="com.dualseason.pojo.UserT">
	<!--name指参数名-->
    <constructor-arg name="name" value="世杰"/>
</bean>

<!--第三种根据参数类型设置-->
<bean id="userT" class="com.dualseason.pojo.UserT">
	<constructor-arg type="java.lang.String" value="世杰"/>
</bean>

测试

@Test
public void testT(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserT user = (UserT) context.getBean("userT");
    user.show();
}

结论 :在配置文件加载的时候。其中管理的对象都已经初始化了!

6.Spring配置

  1. 别名

alias 设置别名,为bean设置别名,可以设置多个别名

<!--设置别名 : 在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>

  1. bean的配置
<!--bean就是Java对象,由Spring创建和管理-->
<!--
	id是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
	如果配置id,又配置了name,那么name就是别名
	name可以设置多个别名,可以用逗号,分号,空格隔开
	如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
	class是bean的全限定名 = 包名 + 类名
-->
<bean id="hello" name="helloAlias" class="com.dualseason.pojo.Hello">
  <property name="name" value="世杰"/>  
</bean>

  1. import
<import resource="{path}/beans.xml"/>

7. 依赖注入 Dependency Injection

  1. 概念
  • 依赖注入(Dependency Injection)
  • 依赖 :指Bean对象的创建依赖于容器,bean对象的依赖资源
  • 注入 : 指Bean对象所依赖的资源,由容器来设置和装配
  1. 构造器注入(上面已经有了,略)
  2. Set注入

要求被注入的属性,必须有set方法,set方法的方法名由set+属性首字母大写,如果属性是boolean类型,没有set方法,是is

测试pojo类

Address.java

public class Address {

    private String address;

    public String getAddress() {
        return address;
    }

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

Student.java

 package com.dualseason.pojo;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.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 void setName(String name) {
         this.name = name;
    }
     public void setAddress(Address address) {
         this.address = address;
    }
     public void setBooks(String[] books) {
         this.books = books;
    }
     public void setHobbys(List<String> hobbys) {
         this.hobbys = hobbys;
    }
     public void setCard(Map<String, String> card) {
         this.card = card;
    }
     public void setGames(Set<String> games) {
         this.games = games;
    }
     public void setWife(String wife) {
         this.wife = wife;
    }
     public void setInfo(Properties info) {
         this.info = info;
    }
     public void show(){
         System.out.println("name="+ name
                 + ",address="+ address.getAddress()
                 + ",books="
        );
         for (String book:books){
             System.out.print("<<"+book+">>\t");
        }
         System.out.println("\n爱好:"+hobbys);
         System.out.println("card:"+card);
         System.out.println("games:"+games);
         System.out.println("wife:"+wife);
         System.out.println("info:"+info);
    }
 }

(1) 常量注入

<bean id="student" class="com.dualseason.pojo.Student">
	<property name="name" value="世杰"/>
</bean>

测试 :

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Student student = (Student) context.getBean("student");
    System.out.println(student.getName());
}

(2) Bean注入

注意点 : 这里的值是一个引用 , ref

<bean id="address" class="com.dualseason.pojo.Address">
	<property name="address" value="湛江"/>
</bean>
<bean id="student" class="com.dualseason.pojo.Student">
    <property name="name" value="世杰"/>
    <property name="address" ref="address"/>
</bean>

(3) 数组注入

<bean id="student" class="com.dualseason.pojo.Student">
	<property name="name" value="世杰"/>
    <property name="address" ref="address">
    <property name="books">
        <array>
            <value>西游记</value>
            <value>红楼梦</value>
            <value>水浒传</value>
        </array>    
    </property>
</bean>

(4) List注入

<property name="hobbys">
	<list>
    	<value>听歌</value>
        <value>看电影</value>
        <value>爬山</value>
    </list>
</property>

(5) Map注入

<property name="card">
	<map>
    	<entry key="中国邮政" value="6846541879815"/>
        <entry key="建设" value="13548943165489"/>
    </map>
</property>

(6) set注入

<property name="games">
	<set>
    	<value>LOL</value>
        <value>原神</value>
        <value>王者荣耀</value>
    </set>
</property>

(7) NULL注入

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

(8) Properties注入

<property name="info">
	<props>
    	<prop key="学号">201908764217</prop>
        <prop key="性别"></prop>
        <prop key="姓名">世杰</prop>
    </props>
</property>

  1. 命名和c命名注入

User.java【注意 :这里没有有参构造器】

public class User {
     private String name;
     private int age;
 
     public void setName(String name) {
         this.name = name;
    }
 
     public void setAge(int age) {
         this.age = age;
    }
 
     @Override
     public String toString() {
         return "User{" +
                 "name='" + name + '\'' +
                 ", age=" + age +
                 '}';
    }
 }

(1) p命名空间注入 : 需要在头文件中加入约束文件

导入约束 : xmlns:p="http://www.springframework.org/schema/p"
<!--p(属性:properties)命名空间,属性依然要设置set方法-->
<bean id="user" class="com.dualseason.pojo" p:name="世杰" p:age="21"/>

(2) c命名空间注入 : 需要在文件中加入约束文件

导入约束 : xmlns:c="http://www.springframework.org/schema/c"
<!--c(构造:constructor)命名空间,要把有参构造器加上-->
<bean id="user" class="com.dualseason.pojo.User" c:name="世杰" c:age="21"/>

测试代码 :

@Test
public void test02(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = (User) context.getBean("user");
    System.out.println(user);
}

  1. Bean作用域

在Spring中,那些组成应用程序的主体及由Spring Ioc容器所管理的对象,被称为bean。简单地讲,bean就是由IOC容器初始化、装配及管理的对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReactSpring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值