另一个技巧是用静态方法实现实用程序类,该实用程序类可帮助您不仅在托管类中在任何地方使用Spring Bean:
@Componentpublic final class BeanUtil { private static ApplicationContext context; private BeanUtil(ApplicationContext context) { BeanUtil.context = context; } public static <T> T getBean(Class<T> clazz) throws BeansException { Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!"); return context.getBean(clazz); }}


