首页 > 其他分享 >Spring(一)

Spring(一)

时间:2023-01-06 12:46:39浏览次数:34  
标签:容器 Spring bean 组件 注解 IOC

Spring

1.介绍

1.1概述

Spring 是最受欢迎的企业级 Java 应用程序开发框架,数以百万的来自世界各地的开发人员使用Spring 框架来创建性能好、易于测试、可重用的代码。

Spring 框架是一个开源的 Java 平台,它最初是由 Rod Johnson 编写的,并且于 2003 年 6 月首次在 Apache 2.0 许可下发布。

Spring 是轻量级的框架,其基础版本只有 2 MB 左右的大小。

Spring 框架的核心特性是可以用于开发任何 Java 应用程序,但是在 Java EE 平台上构建 web 应用程序是需要扩展的。 Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO编程模型来促进良好的编程实践。

1.2Spring家族

  • Spring Boot:对构建Spring应用程序有自己的见解,并让您尽可能快地启动和运行
  • Spring Framework:为依赖注入、事务管理、web应用、数据访问、消息传递等提供核心支持。
    • Spring 基础框架,可以视为 Spring 基础设施,基本上任何其他 Spring 项目都是以 Spring Framework为基础的。
  • Spring Cloud:为分布式系统中的常见模式提供了一组工具。对于构建和部署微服务非常有用。
  • 还有一系列spring xxx....

1.3Spring Framework特性

  1. 非侵入式
    1. 使用 Spring Framework 开发应用程序时,Spring 对应用程序本身的结构影响非常小。
    2. 对领域模型可以做到零污染;
    3. 对功能性组件也只需要使用几个简单的注解进行标记,完全不会破坏原有结构,反而能将组件结构进一步简化。这
    4. 就使得基于 Spring Framework 开发应用程序时结构清晰、简洁优雅。
  2. 控制反转
    1. IOC——Inversion of Control,翻转资源获取方向。
    2. 把自己创建资源、向环境索取资源变成环境将资源准备好,我们享受资源注入。
  3. 面向切面编程
    • AOP——Aspect Oriented Programming,在不修改源代码的基础上增强代码功能。
  4. 容器
    1. Spring IOC 是一个容器,因为它包含并且管理组件对象的生命周期。
    2. 组件享受到了容器化的管理,替程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发效率。
  5. 组件化
    1. Spring 实现了使用简单的组件配置组合成一个复杂的应用。
    2. 在 Spring 中可以使用 XML和 Java 注解组合这些对象。
    3. 这使得我们可以基于一个个功能明确、边界清晰的组件有条不紊的搭建超大型复杂应用系统。
  6. 声明式
    • 很多以前需要编写代码才能实现的功能,现在只需要声明需求即可由框架代为实现。
  7. 一站式:
    1. 在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。
    2. 而且Spring 旗下的项目已经覆盖了广泛领域,很多方面的功能性需求可以在 Spring Framework 的基础上全部使用 Spring 来实现。

1.4Spring Framework五大功能模块

功能模块 功能介绍
Core Container 核心容器,在 Spring 环境下使用任何功能都必须基于 IOC 容器
AOP&Aspects 面向切面编程
Testing 提供了对 junit 或 TestNG 测试框架的整合。
Data Access/Integration 提供了对数据访问/集成的功能。
Spring MVC 提供了面向Web应用程序的集成功能。

2.IOC

2.1IOC容器

2.1.1IOC思想

IOC:Inversion of Control,翻译过来是反转控制

①获取资源的传统方式

自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程中的全部细节且熟练掌握。

在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加学习成本,同时降低开发效率

②反转控制方式获取资源

点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。

反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源的方式即可,极大的降低学习成本提高开发的效率。这种行为也称为查找的被动形式

③DI

DI:Dependency Injection,翻译过来是依赖注入

DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。

所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现

2.1.2IOC容器在Spring中的实现

Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做 bean。在创建bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:

①BeanFactory

这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。

②ApplicationContext

BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用ApplicationContext 而不是底层的 BeanFactory。

③ApplicationContext的主要实现类
类型名 简介
ClassPathXmlApplicationContext 通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象
FileSystemXmlApplicationContext 通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象
ConfigurableApplicationContext ApplicationContext 的子接口,包含一些扩展方法refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力。
WebApplicationContext 专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中。

2.2基于XML管理的bean

2.2.1入门案例

①创建maven项目
②引入依赖
<dependencies>
    <!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.1</version>
    </dependency>
    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
③创建类HelloSpring
package com.chenchen.Spring.pojo;

public class HelloSpring {
    public void Hello(){
        System.out.println("Hello Spring!");
    }
}
④创建Spring的配置文件
  • 创建方式,名字可任起

    • image-20230105120931360
  • 在Spring的配置文件中配置bean

    • <!--
              配置HelloSpring所对应的bean,即将HelloSpring的对象交给Spring的IOC容器管理.通过bean标签配置IOC容器所管理的bean
                  bean:将对象讲给IOC容器进行管理
                      id:bean的唯一标识,不能重复
                      class:bean对象所对应的类型-->
      <bean id="HelloSpring" class="com.chenchen.Spring.pojo.HelloSpring"></bean>
      
⑤创建测试类
public void testHello() {
    //获取IOC容器对象,参数路径为配置IOC容器的文件路径
    ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取IOC容器的bean
    HelloSpring helloSpring = (HelloSpring) ioc.getBean("HelloSpring");
    //调用HelloSpring类中的方法
    helloSpring.Hello();
}
⑥注意

Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:org.springframework.beans.factory.BeanCreationException: Error creating bean with name'helloworld' defined in class path resource [applicationContext.xml]: Instantiation of beanfailed; nested exception is org.springframework.beans.BeanInstantiationException: Failedto instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nestedexception is java.lang.NoSuchMethodException: com.atguigu.spring.bean.HelloWorld.()

2.2.2获取bean的三种方式

①根据id获取

由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。入门案例用的方式就是id获取

②根据类型获取
applicationContext对象名.getBean(class属性的类型.class);
③根据id和类型获取
applicationContext对象名.getBean(id值,class属性的类型.class);
④注意
  • 当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

  • 当IOC容器中一共配置了两个时就会报错

    • <bean id="HelloSpring1" class="com.chenchen.Spring.pojo.HelloSpring"></bean>
      <bean id="HelloSpring2" class="com.chenchen.Spring.pojo.HelloSpring"></bean>
      
    • org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.chenchen.Spring.pojo.HelloSpring' available: expected single matching bean but found 2: HelloSpring1,HelloSpring2
      
⑤扩展
  • 如果组件类实现了接口,根据接口类型可以获取 bean 吗?
    • 可以,前提是bean唯一
  • 如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
    • 不行,因为bean不唯一
⑥结论

根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

也就是说通过bean类型,bean所继承的类的类型,bean所实现的接口的类型都可以获取bean

2.2.3配置bean时为属性赋值

①property
<bean id="Student" class="com.chenchen.Spring.pojo.Student">
    <!-- property标签:通过组件类的setXxx()方法给组件对象设置属性
                name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关
                value属性:指定属性值 -->
    <property name="id" value="1001"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="18"></property>
</bean>
②构造器
  • 按照有参构造器的this值的顺序依次赋值

  • <bean id="Student" class="com.chenchen.Spring.pojo.Student">
        <!--    public Student(Integer id, String name, Integer age) {
                        this.id = id;
                        this.name = name;
                        this.age = age;
                    }
                    constructor-arg:按照有参构造器的索引依次赋值
                        value:指定属性值
                        index属性:指定参数所在位置的索引(从0开始)
                        name属性:指定参数名
            -->
        <constructor-arg value="1002"></constructor-arg>
        <constructor-arg value="李四"></constructor-arg>
        <constructor-arg value="19"></constructor-arg>
    </bean>
    
③特殊值
null值
  • 需要重新给一个null标签

    <property name="name">
        <null />
    </property>
    
  • 这种方式只是为name赋值一个字符串null

    <property name="name" value="null"></property>
    
XML实体
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<!-- >:&gt;
	 <:&lt; -->
<property name="expression" value="a &lt; b"/>
CDATA节
<property name="name">
    <!-- 解决方案二:使用CDATA节 -->
    <!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
    <!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
    <!-- 所以CDATA节中写什么符号都随意 -->
    <value><![CDATA[<王五>]]></value>
</property>
<!-- <![CDATA[ 这里写什么就是什么 ]]
④为类类型属性赋值
引用外部已声明的bean
<bean name="Student" class="com.chenchen.Spring.pojo.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="赵六"></property>
    <property name="age" value="21"></property>
    <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
    <property name="clazz" ref="clazz"></property>
</bean>
<bean name="clazz" class="com.chenchen.Spring.pojo.Clazz">
    <property name="className" value="java一班"></property>
    <property name="classNumber" value="51"></property>
</bean>

如果错把ref属性写成了value属性,会抛出异常:

Caused by: java.lang.IllegalStateException:Cannot convert value of type 'java.lang.String' to required type'com.atguigu.spring.bean.Clazz' for property 'clazz': no matching editors or conversionstrategy found

意思是不能把String类型转换成我们要的Clazz类型,说明我们使用value属性时,Spring只把这个属性看做一个普通的字符串,不会认为这是一个bean的id,更不会根据它去找到bean来赋值

级联的方式
  • 要保证提前为clazz属性赋值或者实例化

    • <bean name="Student" class="com.chenchen.Spring.pojo.Student">
          <property name="id" value="1004"></property>
          <property name="name" value="赵六"></property>
          <property name="age" value="21"></property>
          <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
          <property name="clazz" ref="clazz"></property>
          <property name="clazz.className" value="java一班"></property>
          <property name="clazz.classNumber" value="51"></property>
      </bean>
      
内部bean
<bean name="Student" class="com.chenchen.Spring.pojo.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="赵六"></property>
    <property name="age" value="21"></property>
    <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
    <property name="clazz">
        <bean class="com.chenchen.Spring.pojo.Clazz">
            <property name="className" value="java一班"></property>
            <property name="classNumber" value="51"></property>
        </bean>
    </property>
</bean>

这种方法即使内部的bean设置了id,也无法通过id和类型的方式进行获取bean

⑤数组类型
<property name="hobby">
    <array>
        <value>唱</value>
        <value>跳</value>
        <value>rap</value>
        <value>篮球</value>
    </array>
</property>
⑥集合类型
list集合
  • 方法一

    • <bean name="clazz" class="com.chenchen.Spring.pojo.Clazz">
          <property name="className" value="java一班"></property>
          <property name="classNumber" value="51"></property>
          <property name="students">
              <list>
                  <ref bean="Student1"></ref>
                  <ref bean="Student2"></ref>
                  <ref bean="Student3"></ref>
                  <ref bean="Student4"></ref>
              </list>
          </property>
      </bean>
      
  • 方法二

    • <bean name="clazz2" class="com.chenchen.Spring.pojo.Clazz">
          <property name="className" value="java一班"></property>
          <property name="classNumber" value="51"></property>
          <property name="students" ref="StudentList"></property>
      </bean>
      <util:list id="StudentList">
          <ref bean="Student1"></ref>
          <ref bean="Student2"></ref>
          <ref bean="Student3"></ref>
          <ref bean="Student4"></ref>
      </util:list>
      

若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可

map集合
  • 方法一

    • <bean id="teacher1" class="com.chenchen.Spring.pojo.Teacher">
          <property name="teacherId" value="1998"></property>
          <property name="teacherName" value="张老师"></property>
      </bean>
      
      <bean id="teacher2" class="com.chenchen.Spring.pojo.Teacher">
          <property name="teacherId" value="1997"></property>
          <property name="teacherName" value="李老师"></property>
      </bean>
      
      <util:map id="teacherMap">
          <entry key="1998" value-ref="teacher1"></entry>
          <entry key="1997" value-ref="teacher2"></entry>
      </util:map>
      
      <bean name="Student5" class="com.chenchen.Spring.pojo.Student">
          <property name="teacherMap" ref="teacherMap"></property>
      </bean>
      
  • 方法二

    • <property name="teacherMap" >
          <map>
              <entry>
                  <key><value>1997</value></key>
                  <bean class="com.chenchen.Spring.pojo.Teacher">
                      <property name="teacherId" value="1998"></property>
                      <property name="teacherName" value="张老师"></property>
                  </bean>
              </entry>
              <entry>
                  <key><value>1997</value></key>
                  <bean class="com.chenchen.Spring.pojo.Teacher">
                      <property name="teacherId" value="1997"></property>
                      <property name="teacherName" value="李老师"></property>
                  </bean>
              </entry>
          </map>
      </property>
      

使用util:list、util:map标签必须引入相应的命名空间,可以通过idea的提示功能选择

⑦p命名空间

引入p命名空间后,可以通过以下方式为bean的各个属性赋值

image-20230105195147741

<bean id="clazz3" class="com.chenchen.Spring.pojo.Clazz"
      p:className="网页一班" p:classNumber="56" p:students-ref="Student4"></bean>

2.2.4引入外部属性文件

  1. 加入依赖

    • <!-- MySQL驱动 -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.16</version>
      </dependency>
      <!-- 数据源 -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.0.31</version>
      </dependency>
      
  2. 创建外部属性文件jdbc.properties

    • jdbc.driver=com.mysql.cj.jdbc.Driver
      jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
      jdbc.username=root
      jdbc.password=123456
      
  3. 创建XML配置文件datasource.xml

    1. 引入属性文件

      • <context:property-placeholder location="jdbc.properties"></context:property-placeholder>
        
    2. 配置bean

      • <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
        
  4. 测试

    • //获取IOC容器对象,参数路径为配置IOC容器的文件路径
      ApplicationContext ioc = new ClassPathXmlApplicationContext("datasource.xml");
      //获取IOC容器的bean
      DataSource bean = ioc.getBean(DataSource.class);
      //获取路径
      Connection connection = bean.getConnection();
      System.out.println(connection);
      

2.2.5bean的作用域

①概念

在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:

取值 含义 创建对象的时机
singleton(默认) 在IOC容器中,这个bean的对象始终为单实例 IOC容器初始化时
prototype 这个bean在IOC容器中有多个实例 获取bean时

如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):

取值 含义
request 在一个请求范围内有效
session 在一个会话范围内有效
②配置bean
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean class="com.chenchen.bean.User" scope="prototype"></bean>

2.2.6bean的生命周期

①具体的生命周期过程
  1. bean对象创建(调用无参构造器)
  2. 给bean对象设置属性
  3. bean对象初始化之前操作(由bean的后置处理器负责)
  4. bean对象初始化(需在配置bean时指定初始化方法)
  5. bean对象初始化之后操作(由bean的后置处理器负责)
  6. bean对象就绪可以使用bean对象销毁(需在配置bean时指定销毁方法)
  7. IOC容器关闭
②配置bean
<!-- 使用init-method属性指定初始化方法 -->
<!-- 使用destroy-method属性指定销毁方法 -->
<!-- initMethod和destroyMethod都是自己在实例类中创建的两个方法 -->
<bean " scope="prototype" init-method="initMethod" destroy-method="destroyMethod">  </bean>
③bean的后置处理器

bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行

  • 创建bean的后置处理器:

    • package com.chenchen.Spring.pojo;
      
      import org.springframework.beans.BeansException;
      import org.springframework.beans.factory.config.BeanPostProcessor;
      
      public class MyBeanProcessor implements BeanPostProcessor {
          @Override
          public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
              System.out.println("--------------后置--------前");
              return bean;
          }
      
          @Override
          public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
              System.out.println("--------------后置--------后");
              return bean;
          }
      }
      
  • 在IOC容器中配置后置处理器:

    • <!-- bean的后置处理器要放入IOC容器才能生效 -->
      <bean id="myBeanProcessor" class="com.chenchen.Spring.pojo.MyBeanProcessor"/>
      

2.2.7FactoryBean

①简介

FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。

将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。

package org.springframework.beans.factory;
import org.springframework.lang.Nullable;
public interface FactoryBean<T> {
    String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
    @Nullable    
    T getObject() throws Exception;
    @Nullable    
    Class<?> getObjectType();
    default boolean isSingleton() {
        return true;   
    }
}
②测试
创建类UserFactoryBean
public class UserFactoryBean implements FactoryBean<User> {
    @Override
    public User getObject() throws Exception {
        return new User();
    }
    @Override
    public Class<?> getObjectType() {
        return User.class;
    }
}
配置bean
<bean id="user" class="com.chenchen.bean.UserFactoryBean"></bean>
使用
@Testpublic void testUserFactoryBean(){
    //获取IOC容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("factorybean.xml");
    User user = (User) ac.getBean("user");
    System.out.println(user);}

2.2.8基于xml的自动装配

自动装配:根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值

①配置bean
  1. 使用bean标签的autowire属性设置自动装配效果
  2. 自动装配方式:byType
    • byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
      • 若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
      • 若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException
  3. 自动装配方式:byName
    • byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值
  4. no和default的都是不自动装配

2.3基于注解管理的bean

2.3.1标记与扫描

①注解

和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。

本质上:所有一切的操作都是Java代码来完成的,XML和注解只是告诉框架中的Java代码如何执行。

举例:元旦联欢会要布置教室,蓝色的地方贴上元旦快乐四个字,红色的地方贴上拉花,黄色的地方贴上气球。

image-20230106110652371

班长做了所有标记,同学们来完成具体工作。墙上的标记相当于我们在代码中使用的注解,后面同学们做的工作,相当于框架的具体操作。

②扫描

Spring 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注解进行后续操作。

③标识组件的常用注解
  1. @Component:将类标识为普通组件
  2. @Controller:将类标识为控制层组件
  3. @Service:将类标识为业务层组件
  4. @Repository:将类标识为持久层组件
  5. @Controller、@Service、@Repository这三个注解只是在@Component注解的基础上起了三个新的名字
  6. 对于Spring使用IOC容器管理这些组件来说没有区别。
    • 所以@Controller、@Service、@Repository这三个注解只是给开发人员看的,让我们能够便于分辨组件的作用
  7. 注意:虽然它们本质上一样,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。
④扫描组件
  1. 最基本的扫描方式

    • <!-- 参数为要扫描的包的路径 -->
      <context:component-scan base-package="com.chenchen"></context:component-scan>
      
  2. 指定要排除的组件

    • <context:component-scan base-package="com.chenchen">
          <!-- context:exclude-filter标签:指定排除规则 -->
          <!--  type:设置排除或包含的依据 
      			type="annotation",根据注解排除,expression中设置要排除的注解的全类名 
      			type="assignable",根据类型排除,expression中设置要排除的类型的全类名 -->    
          <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
          <!--<context:exclude-filter type="assignable" expression="com.chenchen.controller.UserController"/>-->
      </context:component-scan>
      
  3. 仅扫描指定组件

    • <!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 -->
      <!-- use-default-filters属性:取值false表示关闭默认扫描规则 -->
      <!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 -->
      <context:component-scan base-package="com.chenchen" use-default-filters="false">
          <!--  type:设置排除或包含的依据 
                  type="annotation",根据注解排除,expression中设置要排除的注解的全类名 
                  type="assignable",根据类型排除,expression中设置要排除的类型的全类名 -->    
          <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
          <!--<context:include-filter type="assignable" expression="com.chenchen.controller.UserController"/>-->
      </context:component-scan>
      
⑤组件所对应的bean的id

在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。现在使用注解后,每个组件仍然应该有一个唯一标识。

默认情况,类名首字母小写就是bean的id。

例如:UserController类对应的bean的id就是userController。

自定义bean的id可通过标识组件的注解的value属性设置自定义的bean的id

@Service("userService")

默认为userServiceImpl public class UserServiceImpl implementsUserService {}

2.3.2基于注解的自动装配

①@Autowired注解

在成员变量上直接标记@Autowired注解即可完成自动装配,不需要提供setXxx()方法。

  • @Autowired注解可以标记在构造器和set方法
②@Autowired工作流程

image-20230106122816459

  • 首先根据所需要的组件类型到IOC容器中查找
    1. 能够找到唯一的bean:直接执行装配
    2. 如果完全找不到匹配这个类型的bean:装配失败
    3. 和所需类型匹配的bean不止一个
      1. 没有@Qualifier注解:根据@Autowired标记位置成员变量的变量名作为bean的id进行匹配
        1. 能够找到:执行装配
        2. 找不到:装配失败
      2. 使用@Qualifier注解:根据@Qualifier注解中指定的名称作为bean的id进行匹配
        1. 能够找到:执行装配
        2. 找不到:装配失败

@Autowired中有属性required,默认值为true,因此在自动装配无法找到相应的bean时,会装配失败

可以将属性required的值设置为true,则表示能装就装,装不上就不装,此时自动装配的属性为默认值

但是实际开发时,基本上所有需要装配组件的地方都是必须装配的,用不上这个属性。

标签:容器,Spring,bean,组件,注解,IOC
From: https://www.cnblogs.com/Myvlog/p/17030111.html

相关文章