SpingIOC是通过注解依赖注入来实现程序之间的依赖关系,达到解耦的作用。
依赖的方式:a.基于配置文件的注入 b.proc类属性注入
基于配置文件的注入:
project的注入:
这是bean包User对象关于String,int,List,Set,Srting[],Map在配置文件中的的注入
public class User {
private String strValue;
private int intValue;
private List listValue;
private Set setValue;
private String[] strArrayValue;
private Map mapValue;
public String getStrValue() {
return strValue;
}
public void setStrValue(String strValue) {
this.strValue = strValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public List getListValue() {
return listValue;
}
public void setListValue(List listValue) {
this.listValue = listValue;
}
public Set getSetValue() {
return setValue;
}
public void setSetValue(Set setValue) {
this.setValue = setValue;
}
public String[] getStrArrayValue() {
return strArrayValue;
}
public void setStrArrayValue(String[] strArrayValue) {
this.strArrayValue = strArrayValue;
}
public Map getMapValue() {
return mapValue;
}
public void setMapValue(Map mapValue) {
this.mapValue = mapValue;
}
}
这是属性测试
public class PropertyTest {
private ApplicationContext ac;
@Before
public void init(){
ac = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testProperty(){
User user =(User) ac.getBean("user");
System.out.println("strValue="+user.getStrValue());
System.out.println("intValue="+user.getIntValue());
System.out.println("listValue="+user.getListValue());
System.out.println("setValue="+user.getSetValue());
System.out.println("strArrayValue="+user.getStrArrayValue());
System.out.println("mapValue="+user.getMapValue());
}
}
结果:
strValue=I AM A STRVALUE
intValue=1234
listValue=[list1, list2, list3]
setValue=[set1, set2, set3]
strArrayValue=[Ljava.lang.String;@8646db9
mapValue={key1=map1, key2=map2, key3=map3}
这是配置文件
<bean id="user" class="com.fz.spring.bean.User">
<property name="strValue" value="THIS IS A STRVALUE"></property>
<property name="intValue" value="1234"></property>
<property name="listValue">
<list>
<value>list1</value>
<value>list2</value>
<value>list3</value>
</list>
</property>
<property name="setValue">
<set>
<value>setValue1</value>
<value>setValue2</value>
<value>set3Value3</value>
</set>
</property>
<property name="strArrayValue">
<list>
<value>Array1</value>
<value>Array2</value>
<value>sArray3</value>
</list>
</property>
<property name="mapValue">
<map>
<entry key="key1" value="map1"></entry>
<entry key="key2" value="map2"></entry>
<entry key="key3" value="map3"></entry>
</map>
</property>
</bean>