您的位置:首页 > 编程语言 > Java开发

Spring 复杂对象的注入

2016-04-09 00:00 387 查看
摘要: Collection Map 等注入

Spring 复杂对象的注入

复杂对象主要分为有两类:Collection类(包括数组和list)和Map类。

List<String>的注入形式:(数组形式其实是差不多的)

public class OneManBand implements Performer {
public OneManBand() {
}

public void perform() throws PerformanceException {
for (Instrument instrument : instruments) {
instrument.play();
}
}

private Collection<Instrument> instruments;

private Collection<String> names;

public Collection<String> getNames() {
return names;
}

public void setNames(Collection<String> names) {
this.names = names;
}

public void setInstruments(Collection<Instrument> instruments) {
this.instruments = instruments; // <co
// id="co_injectInstrumentCollection"/>
}
public static void main(String args[]){
ApplicationContext ac=new ClassPathXmlApplicationContext("com/springinaction/springidol/springidol-context-2.xml");
OneManBand one=(OneManBand)ac.getBean("oneManBand");
System.out.println(one.getNames());
}
}

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 说明是getter/setter注入-->
<bean id="oneManBand" class="com.springinaction.springidol.OneManBand">
<property name="names">

<list>
<!-- 内部bean	<bean></bean>  -->
<!-- 引用 <ref bean="xx"></ref>  -->
<!-- 常规类型主要就是 就用 value-->
<value>1</value>
<value>nihao</value>
</list>
</property>
</bean>

</beans>

map<String,Integer> 注入:

public class OneManBand implements Performer {

private Collection<Instrument> instruments;

private Map<String,Integer> prices;
public Map<String, Integer> getPrices() {
return prices;
}

public void setPrices(Map<String, Integer> prices) {
this.prices = prices;
}

public static void main(String args[]){
ApplicationContext ac=new ClassPathXmlApplicationContext("com/springinaction/springidol/springidol-context-2.xml");
OneManBand one=(OneManBand)ac.getBean("oneManBand");
System.out.println(one.getPrices());
}
}

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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
<bean id="oneManBand" class="com.springinaction.springidol.OneManBand">
<property name="prices">
<map>
<entry key="1" value="2"></entry>
<entry key="2" value="3"></entry>
</map>
</property>
</bean>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: