1.3、获取bean
@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有且只能有一个
<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
..

浙公网安备 33010602011771号