集合装配
如果bean中有一些集合属性,配置文件的配置如下
package com.bjsxt.dao.impl; import java.util.List; import java.util.Map; import java.util.Set; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserDAOImpl implements UserDAO { /* (non-Javadoc) * @see com.bjsxt.dao.UserDAO#save(com.bjsxt.model.User) */ private Set<String> sets; private List<String> lists; private Map<String , String> maps; public Set<String> getSets() { return sets; } public void setSets(Set<String> sets) { this.sets = sets; } public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public Map<String, String> getMaps() { return maps; } public void setMaps(Map<String, String> maps) { this.maps = maps; } public UserDAOImpl() { } public void save(User user) { System.out.println("user saved!"); } @Override public String toString() { return "sets size:" + sets.size() + "| lists size:" + lists.size() + "| maps size:" + maps.size() ; } }
具有集合属性的UserDAOImpl
<?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-2.5.xsd"> <bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl"> <property name="sets"> <set> <value>1</value> <value>2</value> </set> </property> <property name="lists"> <list> <value>1</value> <value>2</value> <value>3</value> </list> </property> <property name="maps"> <map> <entry key="1" value="1"></entry> <entry key="2" value="2"></entry> <entry key="3" value="3"></entry> <entry key="4" value="4"></entry> </map> </property> </bean> <bean id="userService" class="com.bjsxt.service.UserService"> <!-- <property name="userDAO"> <ref bean="userDAO"/> </property> --> <constructor-arg> <ref bean="userDAO"/> </constructor-arg> </bean> </beans>
配置文件
自动装配
如果每个属性都使用ref配置,一个大项目的Spring配置会十分庞大,可以通过<bean>的autowire属性设置自动装配规则。使用后不需要再用<property>子标签设置该bean的属性、依赖关系。Spring会根据反射,自动寻找符合该条件的属性,设置到该bean属性上。如果autowire设置为byType,将会按照属性的类型自动装配,注意如果找到多个该属性类型的bean,会抛出异常。如果是byName,根据名称自动装配,例如如果bean中有个名为datasource的属性,Spring会把id为datasource的bean设置到该bean中
Bean的生命周期
时间: 2024-10-10 09:31:54