1.导入Spring的核心包 。
创建class A加有属性 string list map properties 还有一test()方法用以测试输出 。
public class A {
private String str;
private List list;
private Map map;
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setMap(Map map) {
this.map = map;
}
public void setList(List list) {
this.list = list;
}
public void setStr(String str) {
this.str = str;
}
public void test(){
System.out.println("str==>"+str);
System.out.println("list==>"+list);
System.out.println("map==>"+map);
System.out.println("Properties==>"+properties);
}
}
------------------------------
2.创建class B 用于构造注入和spring ref 关联
public class B {
private String name;
private int age;
public B(){}
//有参构造
public B(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "B--------->"+name+age;
}
}
-------------------------------
3.用于测试的class Test.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext acx=new ClassPathXmlApplicationContext("/ApplicationContext.xml");
A a=(A) acx.getBean("a");
a.test();
}
}
-----------------------------------
4.建spring 的applicationcontext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="b" class="com.fit.B">
<constructor-arg value="nihao" index="0"/><!-- 通过构造参数实例化Bean -->
<constructor-arg value="20" index="1"/>
</bean>
<bean id="a" class="com.fit.A"><!-- 多个属性 String str,List list,Map map, properties -->
<property name="str" value="您好"/><!-- 赋值 -->
<property name="list"><!-- 集合 -->
<list>
<value>123</value>
<value>456</value>
<ref bean="b"/><!-- 集合 对象 -->
</list>
</property>
<property name="map">
<map>
<entry key="1" value="123456"/><!-- map -->
<entry key="2" value="987665"/>
<entry key="3" value-ref="b"/><!-- map 对象 -->
</map>
</property>
<property name="properties"><!-- 属性 键值对 -->
<value>
a=123
b=456
c=789
</value>
</property>
</bean>
</beans>
运行Test 的main方法 你会看到结果