实例化IoC容器
ApplicationContext context =
new ClassPathXmlApplicationContext("examples.xml");
如果有多个配置文件,则可以使用数组的形式:
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"example1.xml", "example2.xml"});
上面的XML配置文件是文件的路径,是提供给ApplicationContext构造函数的各种外部资源,用于加载元数据.
关于<import />元素:
我们已经知道,可以通过构造函数从配置的xml中加载bean的定义.如果这个构造函数需要多个资源位置,如上所示.或者,可以使用一次或者多次<import />元素加载bean的定义,示例如下:
<beans>
<import resource="examples.xml"/>
<import resource="/resources/example1.xml"/>
<import resource="/resources/example2.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
使用IOC容器:
// 创建和配置bean
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
// 获取配置好的bean
HelloWorld service = context.getBean("helloWorld", HelloWorld.class);
//下面是你需要的业务逻辑
...
...