1.3、获取bean

方式一:根据id获取

@Test
public void testHelloWorld(){
    ApplicationContext ac = newClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld helloworld = (HelloWorld) ac.getBean("helloworld");
    helloworld.sayHello();
}

方式二:根据类型获取

@Test
public void testHelloWorld(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld bean = ac.getBean(HelloWorld.class);
    bean.sayHello();
}

方式三、根据类型和id获取

@Test
public void testHelloWorld(){
    ApplicationContext ac = newClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld bean = ac.getBean("helloworld", HelloWorld.class);
    bean.sayHello();
}

注意

当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

当IOC容器中一共配置了两个:

<bean id="helloworldOne" class="com.atguigu.spring.bean.HelloWorld"></bean>
<bean id="helloworldTwo" class="com.atguigu.spring.bean.HelloWorld"></bean>

会报异常:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean

of type 'com.atguigu.spring.bean.HelloWorld' available: expected single matching bean but

found 2: helloworldOne,helloworldTwo

..

posted @ 2023-03-04 09:23  江南0o0  阅读(26)  评论(0)    收藏  举报