Spring DI 数据类型—— set 方法注入

2024-08-22 15:12

本文主要是介绍Spring DI 数据类型—— set 方法注入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

首先新建项目,可参考 初识IDEA、模拟三层--控制层、业务层和数据访问层

一、spring 环境搭建

(一)pom.xml 导相关坐标

<?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"><modelVersion>4.0.0</modelVersion>
<!--    导坐标,不导入该坐标会影响xml文件创建
导完坐标,一定去该页面右边点开 Maven看看是否下载完成,
若不报错,即下载成功--><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.28</version></dependency></dependencies><groupId>org.example</groupId><artifactId>Spring_ioc_04</artifactId><version>1.0-SNAPSHOT</version>
</project>

(二)搭建配置文件

依次点击:src ==> main ==> resource 右击  ==> New ==> 找 XML Configuration File ==> 找到 Spring Config 并点击,起名(自己随便起名字),为了好区分,我起名叫 applicationContext

(三)建包建类,写方法

        建包建类,可参考模拟三层--控制层、业务层和数据访问层,我们建立 com.apesource路径(这个路径纯纯属于个人习惯,不影响)下的pojo 包。pojo 包写我们的普通的类,我们写个学生类 Student 吧,类中写好成员变量;text 包就写测试类,具体代码如下:

//Student 学生类
package com.apesource.pojo;public class Student {private int sid;private String sname;private int sage;
}
//测试类
package com.apesource.test;public class Test01 {
}

Ok!一切准备就绪,开始演示 DI 数据类型

二、演示 DI 数据类型

2.1 set 注入基本类型与 String

我们要用 setter 方法注入 ,首先得有 set 方法,先去学生类 alt键+ins键 快速生成 set 方法(更多的快捷键使用可以去看看 初识 IDEA)

package com.apesource.pojo;public class Student {private int sid;private String sname;private int sage;public void setSid(int sid) {this.sid = sid;}public void setSname(String sname) {this.sname = sname;}public void setSage(int sage) {this.sage = sage;}
}

 然后去我们的 applicationContext.xml 文件做相关配置【这块想了解更清楚可以点击链接; Spring DI 简单演示三层架构——Setter 注入】。

<?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">
<!--    注入 Student 类--><!--property的name指要通过 setter 给注入的属性名--><!--property的value指要通过 setter 给注入的数据,写具体值--><!--property的ref可以直接引用标签id,Spring DI 简单演示三层架构——set注入有演示--><bean class="com.apesource.pojo.Student" id="student"><property name="sage" value="12"></property><property name="sid" value="1"></property><property name="sname" value="唐三"></property></bean>
</beans>

测试【这块想了解更清楚可点击链接Spring DI 简单演示三层架构——Setter 注入】。

package com.apesource.test;import com.apesource.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test01 {public static void main(String[] args) {//1.加载 Spring 核心配置文件,获取 Spring 容器对象ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//2.获取对象Student student = (Student) applicationContext.getBean("student");System.out.println(student);//返回一个学生的地址}}

测试结果(有地址,测试成功):


如果想看到具体值,我们可以去 Student 类写 get 方法,然后这边调用 get 方法,具体步骤如下:

package com.apesource.pojo;public class Student {private int sid;private String sname;private int sage;public void setSid(int sid) {this.sid = sid;}public void setSname(String sname) {this.sname = sname;}public void setSage(int sage) {this.sage = sage;}
/************************get方法是为了测试调用可以看到具体值*************************/public int getSid() {return sid;}public String getSname() {return sname;}public int getSage() {return sage;}
}
package com.apesource.test;import com.apesource.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test01 {public static void main(String[] args) {//1.加载 Spring 核心配置文件,获取 Spring 容器对象ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//2.获取对象Student student = (Student) applicationContext.getBean("student");System.out.println("对象地址:"+student);//返回一个学生的地址/******************************为了更方便的查看学生信息,我们调用get方法调用**********************************/System.out.println("学生的年龄:"+student.getSage());System.out.println("学生的名字:"+student.getSname());System.out.println("学生的id号:"+student.getSid());}}

测试结果(这个学生的信息就是我们在 application.xml 中创建的信息,测试成功):


如果想看到具体值,我们也可以去 Student 类写 toString 方法,然后测试就可以看到具体值,具体步骤如下:

package com.apesource.pojo;public class Student {private int sid;private String sname;private int sage;public void setSid(int sid) {this.sid = sid;}public void setSname(String sname) {this.sname = sname;}public void setSage(int sage) {this.sage = sage;}
/*********************to String方法为了测试有显示结果****************************/@Overridepublic String toString() {return "Student{" +"sid=" + sid +", sname='" + sname + '\'' +", sage=" + sage +'}';}
}
package com.apesource.test;import com.apesource.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test01 {public static void main(String[] args) {//1.加载 Spring 核心配置文件,获取 Spring 容器对象ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//2.获取对象Student student = (Student) applicationContext.getBean("student");System.out.println(student);//返回一个学生信息}

测试结果:

2.2 set 注入复杂类型【 List 、Map 、Set、array数组、properties 】

         首先,我们建一个新的包新的类,可参考模拟三层--控制层、业务层和数据访问层,我们在 com.apesource路径下的pojo 包里再写个 Collection 集合类吧,类中写好成员变量,我们演示复杂类型,就定义变量为 List 、Map 、Set、array数组、properties  这些复杂的类型:

package com.apesource;import java.util.*;public class Collection {private List list;private Map map;private Set set;private String[] array;private Properties properties;/****************因为使用set注入,要写set方法****************/public void setList(List list) {this.list = list;}public void setMap(Map map) {this.map = map;}public void setSet(Set set) {this.set = set;}public void setArray(String[] array) {this.array = array;}public void setProperties(Properties properties) {this.properties = properties;}/****************为了观察到测试结果的具体值,写 toString方法****************/@Overridepublic String toString() {return "collectionT{" +"list=" + list +", map=" + map +", set=" + set +", array=" + Arrays.toString(array) +", properties=" + properties +'}';}
}

然后去我们的 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"><!--    注入 Collection 类--><bean class="com.apesource.pojo.Collection" id="collection"><!--List集合--><property name="list"><list><value>油条</value><value>玉米</value><value>包子</value><value>红薯</value><value>胡辣汤</value></list></property><!--Map集合——键值对--><property name="map"><map><entry key="红" value="蓝"></entry><entry key="白" value="黑"></entry><entry key="光明" value="黑暗"></entry><entry key="正义" value="邪恶"></entry><entry key="快乐" value="悲伤"></entry></map></property><!--Set集合--><property name="set"><set><value>唐三</value><value>小舞</value><value>戴沐白</value><value>朱竹清</value><value>宁荣荣</value><value>奥斯卡</value><value>胖子</value></set></property><!--数组--><property name="array"><array><value>喜羊羊</value><value>美羊羊</value><value>懒羊羊</value><value>沸羊羊</value><value>暖羊羊</value><value>慢羊羊村长</value></array></property><!--set诸如还支持properties,下面演示--><property name="properties"><props>
<!--                <prop key="键">值</prop>--><prop key="中文">英文</prop><prop key="名字">name</prop><prop key="age">年龄</prop><prop key="语文">数学</prop><prop key="学校">学习</prop></props></property></bean>
</beans>

测试:

package com.apesource.test;import com.apesource.pojo.Collection;
import com.apesource.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;public class Test01 {public static void main(String[] args) {//1.加载 Spring 核心配置文件,获取 Spring 容器对象ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//2.获取对象Collection collection = (Collection)applicationContext.getBean("collection");System.out.println(collection);}}

测试结果(由于所有结果在一行,截图看不完,我将该主要结果复制在下方):

完整结果:

collectionT{list=[油条, 玉米, 包子, 红薯, 胡辣汤], map={红=蓝, 白=黑, 光明=黑暗, 正义=邪恶, 快乐=悲伤}, set=[唐三, 小舞, 戴沐白, 朱竹清, 宁荣荣, 奥斯卡, 胖子], array=[喜羊羊, 美羊羊, 懒羊羊, 沸羊羊, 暖羊羊, 慢羊羊村长], properties={语文=数学, age=年龄, 名字=name, 学校=学习, 中文=英文}}

三、一个类可以被注入多次,但id需唯一

拿简单的学生类做演示吧

学生类不做任何改变,在我们的 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">
<!--    注入 Student 类-->
<!--    property的name指要通过 setter 给注入的属性名-->
<!--    property的value指要通过 setter 给注入的数据,写具体值-->
<!--    property的ref可以直接引用标签id--><bean class="com.apesource.pojo.Student" id="student"><property name="sage" value="12"></property><property name="sid" value="1"></property><property name="sname" value="唐三"></property></bean><bean class="com.apesource.pojo.Student" id="student1"><property name="sage" value="12"></property><property name="sid" value="2"></property><property name="sname" value="小舞"></property></bean>
</beans>

测试:

package com.apesource.test;import com.apesource.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test01 {public static void main(String[] args) {//1.加载 Spring 核心配置文件,获取 Spring 容器对象ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//2.获取对象Student student = (Student) applicationContext.getBean("student");System.out.println(student);//返回一个学生信息Student student1 = (Student) applicationContext.getBean("student1");System.out.println(student1);//返回一个学生信息}
}

测试结果(两个学生都打印出来了,测试成功):

四、总结

DI 数据类型 set 方法可注入三种:

        基本类型与String

        复杂类型,list,set,array,map,properties

        javaBean对象,具体实例可点击链接Spring DI 简单演示三层架构——Setter 注入】

一个类可以被注入多次,但id需唯一

这篇关于Spring DI 数据类型—— set 方法注入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1096631

相关文章

Spring Boot 3 整合 Spring Cloud Gateway实践过程

《SpringBoot3整合SpringCloudGateway实践过程》本文介绍了如何使用SpringCloudAlibaba2023.0.0.0版本构建一个微服务网关,包括统一路由、限... 目录引子为什么需要微服务网关实践1.统一路由2.限流防刷3.登录鉴权小结引子当前微服务架构已成为中大型系统的标

Java集合中的List超详细讲解

《Java集合中的List超详细讲解》本文详细介绍了Java集合框架中的List接口,包括其在集合中的位置、继承体系、常用操作和代码示例,以及不同实现类(如ArrayList、LinkedList和V... 目录一,List的继承体系二,List的常用操作及代码示例1,创建List实例2,增加元素3,访问元

Java中将异步调用转为同步的五种实现方法

《Java中将异步调用转为同步的五种实现方法》本文介绍了将异步调用转为同步阻塞模式的五种方法:wait/notify、ReentrantLock+Condition、Future、CountDownL... 目录异步与同步的核心区别方法一:使用wait/notify + synchronized代码示例关键

Java 8 Stream filter流式过滤器详解

《Java8Streamfilter流式过滤器详解》本文介绍了Java8的StreamAPI中的filter方法,展示了如何使用lambda表达式根据条件过滤流式数据,通过实际代码示例,展示了f... 目录引言 一.Java 8 Stream 的过滤器(filter)二.Java 8 的 filter、fi

Java中实现订单超时自动取消功能(最新推荐)

《Java中实现订单超时自动取消功能(最新推荐)》本文介绍了Java中实现订单超时自动取消功能的几种方法,包括定时任务、JDK延迟队列、Redis过期监听、Redisson分布式延迟队列、Rocket... 目录1、定时任务2、JDK延迟队列 DelayQueue(1)定义实现Delayed接口的实体类 (

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring

将java程序打包成可执行文件的实现方式

《将java程序打包成可执行文件的实现方式》本文介绍了将Java程序打包成可执行文件的三种方法:手动打包(将编译后的代码及JRE运行环境一起打包),使用第三方打包工具(如Launch4j)和JDK自带... 目录1.问题提出2.如何将Java程序打包成可执行文件2.1将编译后的代码及jre运行环境一起打包2

Java使用Tesseract-OCR实战教程

《Java使用Tesseract-OCR实战教程》本文介绍了如何在Java中使用Tesseract-OCR进行文本提取,包括Tesseract-OCR的安装、中文训练库的配置、依赖库的引入以及具体的代... 目录Java使用Tesseract-OCRTesseract-OCR安装配置中文训练库引入依赖代码实

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行

SpringBoot整合easy-es的详细过程

《SpringBoot整合easy-es的详细过程》本文介绍了EasyES,一个基于Elasticsearch的ORM框架,旨在简化开发流程并提高效率,EasyES支持SpringBoot框架,并提供... 目录一、easy-es简介二、实现基于Spring Boot框架的应用程序代码1.添加相关依赖2.添