1. 程式人生 > 其它 >Spring 中 bean 多種資料型別注入

Spring 中 bean 多種資料型別注入

技術標籤:Spring框架springbean

建立實體類

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private int id;
    private String name;
    private Address addresses;
    private Date birthday;
    private List<Hobby> hobbies;
    private Map<String,Hobby> hobbyMap;
    private
Set<Address> addressSet; private Properties info; }

配置bean.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:context="
http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"
>
<bean id="student" class="com.cl.pojo.Student"> <property name="id" value="1"></property> <property name="name" value="小明"></property> <!-- 物件 型別資料注入 --> <property name="addresses" ref="address"></property> <!-- Date日期型別資料注入 --> <property name="birthday" value="2021/1/6"></property> <!-- list型別資料注入 --> <property name="hobbies"> <list value-type="com.cl.pojo.Hobby"> <ref bean="Hobby01"></ref> <ref bean="Hobby02"></ref> </list> </property> <!-- Map型別資料注入 --> <property name="hobbyMap"> <map key-type="java.lang.String" value-type="com.cl.pojo.Hobby"> <entry key="01" value-ref="Hobby01"></entry> <entry key="02" value-ref="Hobby02"></entry> </map> </property> <!-- Set型別資料注入 --> <property name="addressSet"> <set value-type="com.cl.pojo.Address"> <ref bean="address"></ref> </set> </property> <!--properties 配置檔案注入--> <property name="info"> <props> <prop key="userName">root</prop> <prop key="passWord">123456</prop> </props> </property> </bean> <bean id="address" class="com.cl.pojo.Address"> <property name="id" value="1"></property> <property name="address" value="迎風路"></property> </bean> <bean id="Hobby01" class="com.cl.pojo.Hobby"> <property name="id" value="1"></property> <property name="explain" value="打籃球"></property> </bean> <bean id="Hobby02" class="com.cl.pojo.Hobby"> <property name="id" value="2"></property> <property name="explain" value="唱歌"></property> </bean> <bean id="gogo" class="com.cl.pojo.Student" name="s1,s2 s3;s4"> <property name="id" value="1"/> <property name="name" value="小號"/> <property name="addresses" ref="address"/> </bean> </beans>

ApplicationContext獲取 bean

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Spring.xml");
        Student student = (Student) applicationContext.getBean("student");
        System.out.println(student);
    }
}

測試結果:
在這裡插入圖片描述