1.接下来创建多个bean。在上一次基础上创建一个实体类
package com.spring01;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayBye(){
System.out.println("bye"+name);
}
}
在beans.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.xsd">
<bean id="user" class="com.spring01.User">
<!--注入属性,set方式-->
<property name="name">
<value>大黄</value>
</property>
</bean>
<bean id="person" class="com.spring01.Person">
<!--注入属性,set方式-->
<property name="name">
<value>小明</value>
</property>
</bean>
</beans>
在测试类中
import com.spring01.Person;
import com.spring01.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test01 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) ac.getBean("user");
user.sayHello();
Person person = (Person) ac.getBean("person");
person.sayBye();
}
}
输出结果: hello大黄
bye小明。
2然后将两个类建立依赖关系
改变user类
package com.spring01;
public class User{
private String name;
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayHello(){
System.out.println("hello"+name);
person.sayBye();
}
}
这个时候运行测试类,会报空指针异常,因为在user类中person没有被创建。更改beans.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.xsd">
<bean id="user" class="com.spring01.User">
<!--注入属性,set方式-->
<property name="name">
<value>大黄</value>
</property>
<!--引用另一个bean,ref是另一个bean的属性-->
<property name="person" ref="person"/>
</bean>
<bean id="person" class="com.spring01.Person">
<!--注入属性,set方式-->
<property name="name">
<value>小明</value>
</property>
</bean>
</beans>
运行测试类
public class test01 {
@Test
public void test01(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) ac.getBean("user");
user.sayHello();
}
}
结果
hello大黄
bye小明
当new ClasspathXmlApplicationContext("beans.xml")执行,spring容器对象被创建,配置文件中bean被创建。
总结:spring是一种容器框架,配置各种bean,并且维护bean之间的关系。
IOC 传统是把对象的创建和维护对象(bean)放在代码中,现在把这些功能放到spring容器中,所有对于传统方式叫控制反转。另一种叫法DI(依赖注入),从spring角度来说,注入对象,管理各个类之间依赖关系。