com.b510.app.test; org.springframework.context.ApplicationContext; org.springframework.context.support.ClassPathXmlApplicationContext; com.b510.service.AnimalService; SpringTest { main(String[] args) { ApplicationContext act = ClassPathXmlApplicationContext("beans.xml"); AnimalService animalServiceOfDog = (AnimalService) act .getBean("animaleServiceOfDog"); animalServiceOfDog.getInfo(); AnimalService animalServiceOfCat = (AnimalService) act .getBean("animaleServiceOfCat"); animalServiceOfCat.getInfo(); } }
com.b510.service; AnimalService { getInfo(); }
com.b510.service; MeatService { String whatMeat(); }
com.b510.service.impl; com.b510.service.AnimalService; com.b510.service.MeatService; CatServiceBean AnimalService { age; MeatService meatService; getAge() { age; } setAge( age) { .age = age; } @Override getInfo() { System.out.println("我是猫,我的年龄是:"+age+",我很喜欢吃"+meatService.whatMeat()); } MeatService getMeatService() { meatService; } setMeatService(MeatService meatService) { .meatService = meatService; } }
com.b510.service.impl; com.b510.service.AnimalService; com.b510.service.MeatService; DogServiceBean AnimalService { age; MeatService meatService; MeatService getMeatService() { meatService; } setMeatService(MeatService meatService) { .meatService = meatService; } getAge() { age; } setAge( age) { .age = age; } @Override getInfo() { System.out.println("我是狗,我的年龄是:" + age + ",我很喜欢吃" + meatService.whatMeat()); } }
com.b510.service.impl; com.b510.service.MeatService; FishServiceBean MeatService { @Override String whatMeat() { "鱼肉"; } }
com.b510.service.impl; com.b510.service.MeatService; PorkServiceBean MeatService { @Override String whatMeat() { "猪肉"; } }
<div class="cnblogs_code">
2012-3-12 12:58:51 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@c1b531: display name [org.springframework.context.support.ClassPathXmlApplicationContext@c1b531]; startup date [Mon Mar 12 12:58:51 CST 2012]; root of context hierarchy 2012-3-12 12:58:51 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from path resource [beans.xml] 2012-3-12 12:58:54 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory 信息: Bean factory application context [org.springframework.context.support.ClassPathXmlApplicationContext@c1b531]: org.springframework.beans.factory.support.DefaultListableBeanFactory@111a775 2012-3-12 12:58:54 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@111a775: defining beans [meatServiceOfFish,meatServiceOfPork,animaleServiceOfDog,animaleServiceOfCat]; root of factory hierarchy 我是狗,我的年龄是:12,我很喜欢吃猪肉 我是猫,我的年龄是:3,我很喜欢吃鱼肉