Spring属性注入的三种方式(超详细)

简介: Spring属性注入的三种方式(超详细)

首先了解下面两个名词的含义:


IOC:控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。


DI:依赖注入(Dependency Injection,简称DI),就是注入属性。是Spring框架的核心之一。所谓依赖注入,是指程序运行过程中,如果需要调用另一个对象协助时,无须在代码中创建被调用者,而是依赖于外部的注入。Spring的依赖注入对调用者和被调用者几乎没有任何要求,完全支持对POJO之间依赖关系的管理。


DI是IOC中的一种具体实现。


使用set方法进行注入


Book类:


package com.Keafmd.spring5;
/**
 * Keafmd
 *
 * @ClassName: Book
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-14 21:46
 */
/**
 * 演示使用set方法进行注入属性
 */
public class Book {
  //创建属性
    private  String bname;
    private String bauthor;
    private String address;
    //1、set方法注入
    //创建对应的set方法
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public void testdemo(){
        System.out.println(bname+" "+bauthor+" "+address);
    }
}

bean1.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">
    <!-- 一、set方法注入属性-->
    <!-- 1、配置对象的创建-->
    <bean id="book" class="com.Keafmd.spring5.Book">
        <!-- 2、使用property完成属性注入
            name:类里面的属性名称
            value:向属性中注入的值
        -->
        <property name="bname" value="书名"></property>
        <property name="bauthor" value="作者"></property>
        <!--  向属性注入null值-->
        <!--<property name="address" >
            <null/>
        </property>-->
        <!--属性值包含特殊符号
            1.把<>进行转义
            2.把带特殊符号的内容写到CDATA
        -->
    <!-- <property name="address" value="&lt;&lt;北京&gt;&gt;"></property> -->
        <property name="address">
            <value><![CDATA[<<北京>>]]></value>
        </property>
    </bean>
</beans>

测试代码:


package com.Keafmd.spring5.testdemo;
import com.Keafmd.spring5.Book;
import com.Keafmd.spring5.Orders;
import com.Keafmd.spring5.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Keafmd
 *
 * @ClassName: TestSpring5
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-14 20:06
 */
public class TestSpring5 {
    @Test
    public  void testBook(){
        //1、载Spring的配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        //2、获取配置文件中创建的对象  默认是执行无参的构造方法创建
        Book book =applicationContext.getBean("book", Book.class);
        book.testdemo();
    }
}

输出结果:


书名 作者 <<北京>>
Process finished with exit code 0


使用有参构造函数进行注入


Orders类:


package com.Keafmd.spring5;
/**
 * Keafmd
 *
 * @ClassName: Orders
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-14 22:05
 */
/**
 * 使用有参构造注入
 */
public class Orders {
    private String oname;
    private String address;
    public Orders(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }
    public void ordersTest(){
        System.out.println(oname+" "+address);
    }
}

bean1.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="orders" class="com.Keafmd.spring5.Orders">
        <constructor-arg name="oname" value="电脑"/>
        <constructor-arg name="address" value="China"/>
    </bean>
</beans>

测试代码:


package com.Keafmd.spring5.testdemo;
import com.Keafmd.spring5.Book;
import com.Keafmd.spring5.Orders;
import com.Keafmd.spring5.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Keafmd
 *
 * @ClassName: TestSpring5
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-14 20:06
 */
public class TestSpring5 {
    @Test
    public  void testOrders(){
        //1、载Spring的配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        //2、获取配置文件中创建的对象  默认是执行无参的构造方法创建
        Orders orders =applicationContext.getBean("orders", Orders.class);
        orders.ordersTest();
    }
}

输出结果:


电脑 China
Process finished with exit code 0


使用p名称空间注入


第一步:添加p名称空间xmlns:p="http://www.springframework.org/schema/p"。

第二步:进行属性注入,在bean标签里。


Book类:


package com.Keafmd.spring5;
/**
 * Keafmd
 *
 * @ClassName: Book
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-14 21:46
 */
/**
 * 演示使用p名称空间注入属性
 */
public class Book {
    private  String bname;
    private String bauthor;
    private String address;
    //3、p名称空间注入
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public void testdemo(){
        System.out.println(bname+" "+bauthor+" "+address);
    }
}

bean1.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"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--三、p名称空间注入属性-->
    <bean id="book" class="com.Keafmd.spring5.Book" p:bname="书名XXX" p:bauthor="作者XXX" p:address="地址XXX">
    </bean>
</beans>

测试代码:


package com.Keafmd.spring5.testdemo;
import com.Keafmd.spring5.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Keafmd
 *
 * @ClassName: TestSpring5
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-01-14 20:06
 */
public class TestSpring5 {
    @Test
    public  void testBook(){
        //1、载Spring的配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        //2、获取配置文件中创建的对象  默认是执行无参的构造方法创建
        Book book =applicationContext.getBean("book", Book.class);
        book.testdemo();
    }
}

输出结果:


书名XXX 作者XXX 地址XXX
Process finished with exit code 0

以上就是Spring属性注入的三种方式。


相关文章
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
547 0
|
Java Spring
在使用Spring的`@Value`注解注入属性值时,有一些特殊字符需要注意
【10月更文挑战第9天】在使用Spring的`@Value`注解注入属性值时,需注意一些特殊字符的正确处理方法,包括空格、引号、反斜杠、新行、制表符、逗号、大括号、$、百分号及其他特殊字符。通过适当包裹或转义,确保这些字符能被正确解析和注入。
1187 3
|
Java 测试技术 程序员
为什么Spring不推荐@Autowired用于字段注入?
作为Java程序员,Spring框架在日常开发中使用频繁,其依赖注入机制带来了极大的便利。然而,尽管@Autowired注解简化了依赖注入,Spring官方却不推荐在字段上使用它。本文将探讨字段注入的现状及其存在的问题,如难以进行单元测试、违反单一职责原则及易引发NPE等,并介绍为何Spring推荐构造器注入,包括增强代码可读性和维护性、方便单元测试以及避免NPE等问题。通过示例代码展示如何将字段注入重构为构造器注入,提高代码质量。
817 1
|
XML Java 数据格式
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
这篇文章是Spring5框架的实战教程,主要介绍了如何在Spring的IOC容器中通过XML配置方式使用外部属性文件来管理Bean,特别是数据库连接池的配置。文章详细讲解了创建属性文件、引入属性文件到Spring配置、以及如何使用属性占位符来引用属性文件中的值。
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
|
Java 测试技术 数据库
Spring Boot中的项目属性配置
本节课主要讲解了 Spring Boot 中如何在业务代码中读取相关配置,包括单一配置和多个配置项,在微服务中,这种情况非常常见,往往会有很多其他微服务需要调用,所以封装一个配置类来接收这些配置是个很好的处理方式。除此之外,例如数据库相关的连接参数等等,也可以放到一个配置类中,其他遇到类似的场景,都可以这么处理。最后介绍了开发环境和生产环境配置的快速切换方式,省去了项目部署时,诸多配置信息的修改。
|
XML druid Java
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
381 0
|
Java Spring
一键注入 Spring 成员变量,顺序编程
介绍了一款针对Spring框架开发的插件,旨在解决开发中频繁滚动查找成员变量注入位置的问题。通过一键操作(如Ctrl+1),该插件可自动在类顶部添加`@Autowired`注解及其成员变量声明,同时保持光标位置不变,有效提升开发效率和代码编写流畅度。适用于IntelliJ IDEA 2023及以上版本。
386 2
一键注入 Spring 成员变量,顺序编程
|
Java 数据库 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
915 0
|
Java 微服务 Spring
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
在微服务架构中,随着业务复杂度增加,项目可能需要调用多个微服务。为避免使用`@Value`注解逐一引入配置的繁琐,可通过定义配置类(如`MicroServiceUrl`)并结合`@ConfigurationProperties`注解实现批量管理。此方法需在配置文件中设置微服务地址(如订单、用户、购物车服务),并通过`@Component`将配置类纳入Spring容器。最后,在Controller中通过`@Resource`注入配置类即可便捷使用,提升代码可维护性。
380 0
|
XML Java 数据格式
Spring5入门到实战------4、IOC容器-Bean管理XML方式、集合的注入(二)
这篇文章是Spring5框架的实战教程,主题是IOC容器中Bean的集合属性注入,通过XML配置方式。文章详细讲解了如何在Spring中注入数组、List、Map和Set类型的集合属性,并提供了相应的XML配置示例和Java类定义。此外,还介绍了如何在集合中注入对象类型值,以及如何使用Spring的util命名空间来实现集合的复用。最后,通过测试代码和结果展示了注入效果。
Spring5入门到实战------4、IOC容器-Bean管理XML方式、集合的注入(二)