Spring工厂类的其他方法:
引入依赖:pom.xml:
4.0.0 com.itheima spring021.0-SNAPSHOT junit junit4.11 test org.springframework spring-context5.1.14.RELEASE
先创建Person类:
package com.itheima;
public class Person {
}
创建配置文件applicationContext.xml:
测试类:
package com.itheima;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
//Spring的第一个程序
@Test
public void test1(){
//1.获得spring的工厂
ApplicationContext ctx=new ClassPathXmlApplicationContext("/applicationContext.xml");
//2.通过工厂类获得对象
Person person =(Person) ctx.getBean("person");
System.out.println("Person="+person);
}
@Test
public void test2(){
//1.获得spring的工厂
ApplicationContext ctx=new ClassPathXmlApplicationContext("/applicationContext.xml");
//2.通过工厂类获得对象的重载方法2 不清强制类型转换
// Person person = ctx.getBean("person", Person.class);
// System.out.println("Person="+person);
//这个方法,需要Spring工厂配置文件中只能有一个
第一个测试结果:
第二个方法的测试结果:
1.
2.因为配置问价有2个beanPerson类型的类,所以会报异常
3.
4.
5.
6.配置问价没有a类
方法3测试结果:
需要把配置文件中创建一个没有id的bean标签,并把有id的bean注释:
测试4



