一、获取 Bean 对象
1.1 根据名称获取 Bean 对象
由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。
1.确保存在一个测试类:
java
public class HelloWorld {
public void sayHello(){
System.out.println("helloworld");
}
}
2.通过名称获取 Bean 对象
java
<?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="helloWorld" class="Test.HelloWorld"></bean>
</beans>
1.2 根据类型查找 Bean 对象
java
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//HelloWorld helloWorld = (HelloWorld)applicationContext.getBean("helloWorld");
HelloWorld helloWorld =(HelloWorld)applicationContext.getBean(HelloWorld.class);
helloWorld.sayHello();
log.info("日志输出完成");
}
1.3 根据名称和类型查找 Bean 对象
java
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//HelloWorld helloWorld = (HelloWorld)applicationContext.getBean("helloWorld");
//HelloWorld helloWorld =(HelloWorld)applicationContext.getBean(HelloWorld.class);
HelloWorld helloWorld =(HelloWorld)applicationContext.getBean("helloWorld",HelloWorld.class);
helloWorld.sayHello();
log.info("日志输出完成");
}
1.4 如果存在相同类型的多个Bean对象
1.类型相同名称不同的多个Bean对象,可以通过名称的不同查找到对象
2.类型相同名称不同的多个Bean对象,如果通过类型查找会报错:

3.建议根据 名称+类型 的方式进行Bean对象的查找
获取Bean对象的方式需要确保获取对象的唯一性