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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。