Spring学习实验二:根据IOC容器中bean的类型来获取bean的实例

优势

	获取到的对象不用进行强转

劣势

	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);
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值