Spring普通属性的注入
JavaBean代码,需要被注入的Bean:
package com.cos.entity;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class UserBean {
private String name;
private int age;
private String[] phone;
private Map<String, String> son;
private List store;
private Set school;
public Set getSchool() {
return school;
}
public void setSchool(Set school) {
this.school = school;
}
public List getStore() {
return store;
}
public void setStore(List store) {
this.store = store;
}
public Map<String, String> getSon() {
return son;
}
public void setSon(Map<String, String> son) {
this.son = son;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getPhone() {
return phone;
}
public void setPhone(String[] phone) {
this.phone = phone;
}
}
Spring 配置文件 applicationContext.xml ,配置需要注入的Bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
<!-- 普通属性注入 -->
<bean id="userBean" class="com.cos.entity.UserBean">
<!-- String -->
<property name="name" value="zhangsan"/>
<!-- int -->
<property name="age" value="20"/>
<!-- 数组 -->
<property name="phone">
<list>
<value>13817337235</value>
<value>88025222</value>
</list>
</property>
<!-- Map -->
<property name="son">
<map>
<entry key="first" value="son1"/>
<entry key="secend" value="son2"/>
</map>
</property>
<!-- List -->
<property name="store">
<list>
<value>store1</value>
<value>store2</value>
</list>
</property>
<!-- Set -->
<property name="school">
<set>
<value>school1</value>
<value>school2</value>
</set>
</property>
</bean>
</beans>
其中JavaBean里面的属性名和xml文件中的property的name应保持一致。
测试类:
package com.cos.entity;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//通过spring配置文件返回Bean的工厂对象
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
//Bean工厂通过Bean的id得到JavaBean
UserBean ub = (UserBean) factory.getBean("userBean");
System.out.println(""+ub.getName());
System.out.println(""+ub.getAge());
System.out.println(""+ub.getPhone());
System.out.println(""+ub.getSon());
System.out.println(""+ub.getStore());
System.out.println(""+ub.getSchool());
}
}
Spring属性注入详解
1316

被折叠的 条评论
为什么被折叠?



