<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <beanid="accountDao"class="com.flydean.daos.JpaAccountDao"><!-- additional collaborators and configuration for this bean go here --> </bean> <beanid="itemDao"class="com.flydean.daos.JpaItemDao"><!-- additional collaborators and configuration for this bean go here --> </bean><!-- more bean definitions for data access objects go here --></beans>
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"><!-- services --> <beanid="petStore"class="com.flydean.services.PetStoreService"> <propertyname="accountDao"ref="accountDao"/> <propertyname="itemDao"ref="itemDao"/><!-- additional collaborators and configuration for this bean go here --> <constructor-argref="accountDao"/> </bean><!-- more bean definitions for services go here --></beans>
ApplicationContext是高级工厂的接口,它能够维护不同bean的注册及其依赖。通过使用方法T getBean(String name, Class requiredType),获取到bean的实例。 ApplicationContext允许您读取bean定义并访问它们,如下例所示:
// create and configure beansApplicationContext context =newClassPathXmlApplicationContext("services.xml","daos.xml");// retrieve configured instancePetStoreService service =context.getBean("petStore",PetStoreService.class);// use configured instanceList<String> userList =service.getUsernameList();
上面讲到了groovy bean配置, 下面是怎么使用groovy bean:
// create and configure beans with groovy//daos.groovy 必须写在services.groovy前面,否则会报bean找不到的错误ApplicationContext context =newGenericGroovyApplicationContext("daos.groovy","services.groovy");// retrieve configured instancePetStoreService service =context.getBean("petStore",PetStoreService.class);// use configured instanceList<String> userList =service.getUsernameList();
GenericApplicationContext context =newGenericApplicationContext();//reader with xmlnewXmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml","daos.xml");