控制反转(IOC)
public class bean1 {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class student {
private String name;
private List<String> listValue;
private Set<String> setValue;
private Map mapValue;
private Properties proValue;
private bean1 bean1;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getListValue() {
return listValue;
}
public void setListValue(List<String> listValue) {
this.listValue = listValue;
}
public Set<String> getSetValue() {
return setValue;
}
public void setSetValue(Set<String> setValue) {
this.setValue = setValue;
}
public Map getMapValue() {
return mapValue;
}
public void setMapValue(Map mapValue) {
this.mapValue = mapValue;
}
public Properties getProValue() {
return proValue;
}
public void setProValue(Properties proValue) {
this.proValue = proValue;
}
public bean1 getBean1() {
return bean1;
}
public void setBean1(bean1 bean1) {
this.Bean1 = Bean1;
}
@Override
public String toString() {
return "test{" +
"name='" + name + '\'' +
", listValue=" + listValue +
", setValue=" + setValue +
", mapValue=" + mapValue +
", proValue=" + proValue +
'}';
}
}
spring帮创建对象
id为唯一标识符,外界通过它来沟通,通常和类名保持一致
applicationCotext.xml
<bean id ="student" class="com.spdb.gr.father">
<property name = "name" value = "郭"><property>
<property name = "listValue">
<list>
<value>list1</value>
<value>list2</value>
</list>
<property>
<property name = "setValue">
<set>
<value>set1</value>
<value>set2</value>
</set>
<property>
<property name = "mapValue">
<map>
<entry key = "key1" value = "value1"></entry>
<entry key = "key2" >
<value>value2</value>
</entry>
</map>
<property>
<--Properties 类的具体使用。以key=value 的 键值对的形式进行存储值。 key值不能重复。-->
<property name = "propValue">
<props>
<prop key = "propKey1">propValue1</prop>
<prop key = "propKey2">propValue2</prop>
</props>
<property>
<--此处做对象的引用-->
<property name = "bean1" ref= "bean1"><property>
</bean>
<bean id ="bean1" class="com.spdb.gr.bean1">
<property name = "name" value = "郭"><property>
<property name = "age" value = "18"><property>
</bean>
注意:先读取,后创建(对象),最后引用(意为如果某一个bean中引用了其他对象,那就在最后一步进行引用(所以不会因为bean1在student之后,导致引用不上!!!))
test(一运行他就能获取applicationCotext.xml文件,加载此文件的时候就会创建bean对象了,可以在构造方法写一个打印语句,可以查看到她显现出来)
public class SingletonDemo {
public SingletonDemo() {
System.out.println("进来了");
}
public void testSpring(){
ApplicationCotext context = new ClassPathXmlApplicationContext("applicationCotext.xml");
//此处为获取bean中的对象,第一个参数为bean中的id,第二个为对象类型
Student student = context.getBean("student",Student.class);
System.out.println("student.baen1.age = "+ student.getBean1.getAge());
System.out.println(student);
}
}