之前教大家如何创建了一个简单的Spring项目[Spring项目搭建,如何通过Spring创建对象_小魏快起床的博客-CSDN博客],也通过工厂获取到了类对象,体现了IOC的核心,创建对象由Spring容器进行创建,在获取的时候用到了getBean方法,那我们来看看getBean有哪些其他使用方式呢?
1、上面图里面的getBean的方式解释:
第一种是根据类型进行获取
第二种是根据名字或者id进行获取
第三种是根据名字和类型进行获取
2、代码操作
①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="animal" class="cn.xjxwc666.spring.Animal"></bean>
</beans>
②代码编写
public class SpringTest {
@Test
public void test() throws Exception{
//创建一个容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//从容器中根据类型获取对象
Animal bean = context.getBean(Animal.class);
System.out.println(bean);
//从容器中根据名字获取对象
Object animal = context.getBean("animal");
System.out.println(animal);
//从容器中根据名字和对象进行获取
Animal contextBean = context.getBean("animal", Animal.class);
System.out.println(contextBean);
}
}
3、效果图
总结三种:
第一种根据类型获取可以直接获取到该类型的对象
第二种根据名字获取是以object对象接收,后期可能需要强转
第三种是前两种结合,推荐使用第三种