Spring各种类型变量set依赖注入的方法
一、依赖注入的两种方式:构造器注入和set注入。今天我们来说的就是set注入方式。
首先推荐Spring的中文文档链接:https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference
下面所记录的文档中都有详细的介绍,但是个人感觉文档缺点就是记录的太过于杂乱。
package com.ly.pojo; import java.util.*; public class Student {
//字符串类型 private String name;
//Bean类型 private Address address;
//数组类型 private String[] book;
//列表类型 private Listhobbies;
//Map类型 private Mapcard;
//Set类型 private Setgames;
//空类型 private String wife;
//properties类型 private Properties iinfo; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String[] getBook() { return book; } public void setBook(String[] book) { this.book = book; } public ListgetHobbies() { return hobbies; } public void setHobbies(List hobbies) { this.hobbies = hobbies; } public Map getCard() { return card; } public void setCard(Map card) { this.card = card; } public Set getGames() { return games; } public void setGames(Set games) { this.games = games; } public String getWife() { return wife; } public void setWife(String wife) { this.wife = wife; } public Properties getIinfo() { return iinfo; } public void setIinfo(Properties iinfo) { this.iinfo = iinfo; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", address=" + address.toString() + ", book=" + Arrays.toString(book) + ", hobbies=" + hobbies + ", card=" + card + ", games=" + games + ", wife='" + wife + '\'' + ", iinfo=" + iinfo + '}'; } }
下面是配置文件:这里需要注意的是要区分将map和peoperties对比了解。
map中的key和value是通过<entry key="身份证" value="123456789"/>
而peoperties是<prop key="学号">20183763prop>,value的值是写在中间的。
下面的代码中我将其两个写在了一块,便于对比。
<?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="address" class="com.ly.pojo.Address"> <property name="address" value="甘肃省庆阳市南大街"/> bean> <bean id="student" class="com.ly.pojo.Student"> <property name="name" value="凌云"/> <property name="address" ref="address"/> <property name="book"> <array> <value>红楼梦value> <value>西游记value> <value>水浒传value> <value>三国演义value> array> property> <property name="hobbies" > <list> <value>听歌曲value> <value>敲代码value> <value>看电影value> list> property> <property name="card"> <map> <entry key="身份证" value="123456789"/> <entry key="银行卡" value="5555555555"/> map> property> <property name="iinfo"> <props> <prop key="学号">20183763prop> <prop key="性别">男prop> <prop key="姓名">凌云prop> props> property> <property name="games"> <set> <value>LOLvalue> <value>COCvalue> <value>BOBvalue> set> property> <property name="wife" > <null/> property> bean> beans>