优势
获取到的对象不用进行强转
劣势
IOC容器中有多个相同类的对象的时候会报错,无法获取
Person类
package Test;
public class Person {
private String name;
private int age;
private String grade;
private String email;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", grade=" + grade + ", email=" + email + "]";
}
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 String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
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">
<!-- 注册一个Person对象,Spring会自动创建这个Person对象 -->
<!-- 一个bean标签注册一个组件
class:写要注册的组件的全类名(包名加类名)
id:这个对象的唯一标识
-->
<bean class="Test.Person" id="person01">
<!-- 使用property为这个对象的属性赋值 name为属性名,value为属性值 -->
<property name="name" value="张三"></property>
<property name="age" value="12"></property>
<property name="grade" value="四"></property>
<property name="email" value="123456789@qq.com"></property>
</bean>
</beans>
测试
package Test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class IOC {
private ApplicationContext ioc=new ClassPathXmlApplicationContext("IOC.xml");
@Test
public void test02(){
//如果容器中有多个该类的对象不能使用类来进行获取,会报错
//错误:org.springframework.beans.factory.NoUniqueBeanDefinitionException:
//No qualifying bean of type [Test.Person] is defined: expected single matching bean but found 2: person01,person02
Person bean = ioc.getBean(Person.class);
System.out.println(bean);
Person bean2 = ioc.getBean("person01", Person.class);//同时运用id和类型,也不用强转
System.out.println(bean2);
}
}