获取bean的两种方式

BeanFactory方式:

1:

public void testFactory(){
        ResourcePatternResolver rpt=new PathMatchingResourcePatternResolver();
        Resource resource=rpt.getResource("com/test/applicationContext.xml");
        BeanFactory bf=new XmlBeanFactory(resource);
        Dog dog=(Dog) bf.getBean("dog");
        dog.shou();
    }

2:

@Test
    public  void test2(){
        XmlBeanFactory factory=new XmlBeanFactory(
                new ClassPathResource("com/test/applicationContext.xml"));
        IService hello=(IService) factory.getBean("serviceImpl");
        hello.service("Helloween");
    }

ApplicationContext方式:

public void testContext(){
        ApplicationContext ac=
            new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
        Dog dog=(Dog) ac.getBean("dog");
        dog.shou();
        System.out.println(dog.getName()+"\t"+dog.getAge());
    }

 

posted @ 2016-05-04 11:05  guodaxia  阅读(169)  评论(0编辑  收藏  举报