[除了使用XML配置外,还可以选择使用基于注解(annotation)的配置方式,其依赖于字节码来织入组件。注解注入在XML注入之前完成,因此在XML配置中可以重载注解注入的属性。
一、建一个SpringUtil类
package com.ceopen.eoss.spring; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { SpringUtil.applicationContext = context; } public static Object getBean(String name){ return applicationContext.getBean(name); } }
将SpringUtil注入spring配置文件[Spring IoC容器中Bean的作用范围详解 作用域将对Bean的生命周期和创建方式产生影响. singleton 在spring IOC容器中仅存在一个Bean实例,Bean以单实例的方式存在. ]
二、如下取得注入Spring 中的对象
ICBMission icbMission = (ICBMission)SpringUtil.getBean("ICBMission");[在上一小节中,演示了如何使用代码层次上的注解来配置元数据。但是,大量的基础bean还是显式的定义在XML文件中,注解只是用来完成依赖注入。该小节提供了一种选择,通过扫