【Spring学习笔记 四】Spring自动装配机制实践

简介: 【Spring学习笔记 四】Spring自动装配机制实践

我们一般学习某个知识,一定会现有个较为复杂的配置让你理解其中的关系,这个配置清晰规整,但是可能会需要大量的配置,这个时候就会有约定大于配置的理论实现了,通过我们约定好的一致的名称,我可以少写很多对应关系,例如MyBatis中如果数据库表的字段名和模型Model的字段名一致,那么就不需要结果集映射了。同样的在Spring中如果我们约定好一些规则,也能减少XML的配置。本篇Blog我们依然基于XML配置进行介绍,基于注解配置和Java类配置的实现方式统一在后续Blog介绍。

自动装配概念

自动装配是使用spring满足bean依赖的一种方法,spring会在应用上下文中为某个bean寻找其依赖的bean。Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  • 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean
  • 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI

组件扫描和自动装配组合发挥巨大威力,使得显式的配置降低到最少,换句话说:Spring 容器可以在不使用<constructor-arg>和<property> 元素的情况下自动装配相互协作的 bean 之间的关系,这有助于减少编写一个大的基于 Spring 的应用程序的 XML 配置的数量

自动装配模式

下列自动装配模式,它们可用于指示 Spring 容器为来使用自动装配进行依赖注入。可以使用<bean>元素的 autowire 属性为一个 bean 定义指定自动装配模式

事实上,我们一般不推荐使用constructor的形式,因为当bean存在多个构造器的时候,构造方式太复杂了,所以这里不做详细介绍,我们主要学习下byName和byType的实现方式,当然事实上我们只是通过XML配置来入门理解,实际上用注解实现自动装配更便捷一些。

自动装配限制

当然方便带来的问题就是混乱,所以自动装配也有一些限制:

  • 使用byName进行自动装配时,名称必须一一对应的上,也就是当前bean的属性和其依赖的bean的名称定义相同
  • 使用byType进行自动装配时,类型必须唯一,如果依赖的bean有多个类型相同的,那么会抛异常
  • 使用constructor进行自动装配时,必须让构造器有参,同时如果有多个有参构造器,配置也会非常混乱复杂。

所以方便一般只适用于简单的依赖关系,如果80%的场景是简单关系,那么自动装配很适合使用,也就是说我们不能抛弃规整的XML配置,而是依据场景而定。

自动装配实现

接下来我们实践下这两种实现方式,看看自动装配如何发挥作用的,还拿之前的Person类来举例:

Person类

package com.example.Spring.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Perosn {
    private String name;
    private int age;
    private String[] emails;
    private List<String> interests;
    private Set<String> games;
    private Map<String,String> bankAccountMap;
    private String badHobby;
    private Address address;
    private Properties info;
    public void show(){
        System.out.println("name: "+name);
        System.out.println("age: "+age);
        System.out.print("emails: ");
        for (String email:emails){
            System.out.print(email+" ");
        }
        System.out.println(" ");
        System.out.println("interests: "+interests);
        System.out.println("games: "+games);
        System.out.println("bankAccountMap: "+bankAccountMap);
        System.out.println("badHobby: "+badHobby);
        System.out.println("address: "+address);
        System.out.println("info: "+info);
    }
}

这里的Address即是我们依赖的类,我们测试下对Address的自动装配

<bean id="person" class="com.example.Spring.model.Perosn" >
        <!--常量注入-->
        <property name="name" value="tml"/>
        <!--常量注入-->
        <property name="age" value="30"/>
        <!--array注入-->
        <property name="emails">
            <array>
                <value>12345668@qq.com</value>
                <value>12345668@163.com</value>
                <value>12345668@126.com</value>
            </array>
        </property>
        <!--list注入-->
        <property name="interests">
            <list>
                <value>听歌</value>
                <value>看电影</value>
                <value>爬山</value>
            </list>
        </property>
        <!--Set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>王者荣耀</value>
                <value>使命召唤</value>
            </set>
        </property>
        <!--Map注入-->
        <property name="bankAccountMap">
            <map>
                <entry key="中国邮政" value="456456456465456"/>
                <entry key="建设" value="1456682255511"/>
            </map>
        </property>
        <!--Null注入-->
        <property name="badHobby"><null/></property>
        <!--Bean注入-->
        <property name="address" ref="address"/>
        <!--属性注入-->
        <property name="info">
            <props>
                <prop key="学号">20190604</prop>
                <prop key="性别">男</prop>
                <prop key="姓名">小明</prop>
            </props>
        </property>
    </bean>
    <bean id="address" class="com.example.Spring.model.Address" >
        <property name="cityCode" value="100031"/>
        <property name="cityName" value="北京"/>
    </bean>

非自动实现方式

首先我们来看下之前的非自动装配的实现方式,只截取Address部分的配置,原有的应用方式是这样的:

<bean id="person" class="com.example.Spring.model.Perosn" >
        <!--Bean注入-->
        <property name="address" ref="address"/>
</bean>
<bean id="address" class="com.example.Spring.model.Address" >
        <property name="cityCode" value="100031"/>
        <property name="cityName" value="北京"/>
</bean>

byName自动装配

我们再来看下通过byName自动装配的实现方式,只截取Address部分的配置,新的配置方式如下:

<bean id="person" class="com.example.Spring.model.Perosn" autowire="byName">
</bean>
<bean id="address" class="com.example.Spring.model.Address" >
        <property name="cityCode" value="100031"/>
        <property name="cityName" value="北京"/>
</bean>

当一个bean节点带有 autowire byName的属性时

  1. 装配时将查找其类中所有的set方法名,如果配置中有则使用配置中的
  2. 如果配置中没有则去spring容器中寻找是否有此字符串名称id的对象
  3. 如果有,就取出注入;如果没有,返回null

我们测试下实现:

public class PersonTest {
    @Test
    public void PersonTest(){
        //解析beans.xml文件,生成管理相应的bean对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Perosn person = (Perosn) context.getBean("person");
        person.show();
    }
}

可以发现地址还是能被正常打印出来:

这种方式要求,属性名必须和配置文件中对应对象的id一致,否则会找不到装配对象。

byType自动装配

我们再来看下通过byType自动装配的实现方式,只截取Address部分的配置,新的配置方式如下:

<bean id="person" class="com.example.Spring.model.Perosn" autowire="byType">
</bean>
<bean id="address2" class="com.example.Spring.model.Address" >  //即使属性名称不一致,只要类型匹配上了还是能自动装配
        <property name="cityCode" value="100031"/>
        <property name="cityName" value="北京"/>
</bean>

当一个bean节点带有 autowire byType的属性时

  1. 装配时将查找其类中所有的set方法名,如果配置中有则使用配置中的
  2. 如果配置中没有则去spring容器中寻找是否有此属性类型的对象
  3. 如果有且唯一,就取出注入;如果没有,返回null;如果有且不唯一抛异常

我们测试下实现:

public class PersonTest {
    @Test
    public void PersonTest(){
        //解析beans.xml文件,生成管理相应的bean对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Perosn person = (Perosn) context.getBean("person");
        person.show();
    }
}

可以发现地址还是能被正常打印出来:

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常,例如如果配置为:

<bean id="address" class="com.example.Spring.model.Address" >
        <property name="cityCode" value="100031"/>
        <property name="cityName" value="北京"/>
    </bean>
    <bean id="address2" class="com.example.Spring.model.Address" >
        <property name="cityCode" value="100031"/>
        <property name="cityName" value="北京"/>
    </bean>

就会报如下的异常:

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [applicationContext.xml]: Unsatisfied dependency expressed through bean property 'address'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.Spring.model.Address' available: expected single matching bean but found 2: address,address2
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [applicationContext.xml]: Unsatisfied dependency expressed through bean property 'address'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.Spring.model.Address' available: expected single matching bean but found 2: address,address2
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1516)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1399)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
  at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
  at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
  at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.Spring.model.Address' available: expected single matching bean but found 2: address,address2
  at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:220)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1358)
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1501)

总结一下

本篇Blog对自动装配有了一个大致了解,自动装配的本质实际上就是约定大于配置,通过命名一致的约定或者类型独一无二的约定来减少配置的量,这其实已经有了一些Spring Boot雏形的感觉了,但是需要注意的是,再复杂的场景下,清晰全面的配置还是很有必要的。配置和约定只是两种实现方式,具体选择哪种其实看业务实现。

相关文章
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
本文介绍RAG(检索增强生成)技术,结合Spring AI与本地及云知识库实现学术分析AI应用,利用阿里云Qwen-Plus模型提升回答准确性与可信度。
2926 90
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
|
人工智能 JSON 安全
Spring Boot实现无感刷新Token机制
本文深入解析在Spring Boot项目中实现JWT无感刷新Token的机制,涵盖双Token策略、Refresh Token安全性及具体示例代码,帮助开发者提升用户体验与系统安全性。
1526 4
|
前端开发 Java API
利用 Spring WebFlux 技术打造高效非阻塞 API 的完整开发方案与实践技巧
本文介绍了如何使用Spring WebFlux构建高效、可扩展的非阻塞API,涵盖响应式编程核心概念、技术方案设计及具体实现示例,适用于高并发场景下的API开发。
927 0
|
人工智能 监控 Java
Spring AI Alibaba实践|后台定时Agent
基于Spring AI Alibaba框架,可构建自主运行的AI Agent,突破传统Chat模式限制,支持定时任务、事件响应与人工协同,实现数据采集、分析到决策的自动化闭环,提升企业智能化效率。
Spring AI Alibaba实践|后台定时Agent
|
安全 Java 决策智能
Spring Boot自动装配
Spring Boot自动装配基于“约定优于配置”理念,通过条件化配置与Starters机制,智能推断并加载所需组件,大幅简化开发流程。它实现配置自动化,提升效率,降低维护成本,支持自定义扩展,推动微服务快速构建,是Java生态中开发范式的革新之作。(238字)
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1090 2
|
Java 应用服务中间件 开发者
Spring Boot 技术详解与应用实践
本文档旨在全面介绍 Spring Boot 这一广泛应用于现代企业级应用开发的框架。内容将涵盖 Spring Boot 的核心概念、核心特性、项目自动生成与结构解析、基础功能实现(如 RESTful API、数据访问)、配置管理以及最终的构建与部署。通过本文档,读者将能够理解 Spring Boot 如何简化 Spring 应用的初始搭建和开发过程,并掌握其基本使用方法。
1004 2
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
635 0
|
JSON 前端开发 Java
Spring MVC 核心组件与请求处理机制详解
本文解析了 Spring MVC 的核心组件及请求流程,核心组件包括 DispatcherServlet(中央调度)、HandlerMapping(URL 匹配处理器)、HandlerAdapter(执行处理器)、Handler(业务方法)、ViewResolver(视图解析),其中仅 Handler 需开发者实现。 详细描述了请求执行的 7 步流程:请求到达 DispatcherServlet 后,经映射器、适配器找到并执行处理器,再通过视图解析器渲染视图(前后端分离下视图解析可省略)。 介绍了拦截器的使用(实现 HandlerInterceptor 接口 + 配置类)及与过滤器的区别
1557 0