Spring IOC_04 容器初始化及获取bean

public class IocTest {
    public static void main(String[] args) {
    	// ApplicationContext就是我们的容器了,先实例化出来容器,在从中获得bean
    	// ClassPathXmlApplicationContext:表示从当前classpath路径中获取xml文件的配置
    	// 还可以用new FileSystemXmlApplicationContext("绝对路径")。
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        // 通过beanId来查找容器中的实例,需要强转
        Person person1 = (Person) context.getBean("person1");
        // 通过beanId来查找容器中的实例,通过显式传入bean类型来避免强转
        Person person2 = context.getBean("person2",Person.class);
        // 通过bean类型来查找容器中的实例,如果容器中存在同一类型的bean则报错
        Person person3 = (Person) context.getBean(Person.class);
    }
}

基于Groovy的DSL定义时可以使用以下方式

ApplicationContext context = new GenericGroovyApplicationContext("application.groovy");

当然,也提供了通用的方式

GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml");
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy");
context.refresh();

在这可以思考两个问题:

  • 通过相同的beanId,连续调用两次来得到两个person,那这两个person是同一个对象吗?
  • 每次使用beanId获取person的时候,这个准备好的person是什么时候创建的?get的时候还是容器启动的时候?
发布了14 篇原创文章 · 获赞 0 · 访问量 364

猜你喜欢

转载自blog.csdn.net/weixin_44601009/article/details/104310186