本文依赖springBoot讲解,主要讲解依赖注入的三种方式、不采用依赖注入如何获取Bean,及其springBoot获取properties文件的四种方式;本文是基础文章,不喜勿喷!!! 一、 spring依赖注入的三种方式 二、ApplicationContextAware接口 一般情况下,Spring容易使用声明是配置,只需要在web.xml中配置Listener后,该Listener就会自动初始化Spring容器,我们使用注解直接可以访问Spring中的Bean,无需访问Spring容器本身;在这种情况下,容器中的Bean处于容器的管理,我们无需主动访问Spring容器,只需要接受容器的依赖注入即可。 但是在某些特殊情况下,需要实现的功能需要开发者借助Spring容器才能实现,此时我们就要获取Spring对象;为了获取Spring容器,我们可以让Bean实现ApplicationContextAware接口。 下面的实例为实现了ApplicationContextAware接口的工具类。可以通过其类引用或这个类类型获取Spring容器中的Bean对象: public class ApplicationUtil implements ApplicationContextAware { // Spring 容器对象 private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口, 注入Context到静态变量中. */ @Override public void setApplicationContext(ApplicationContext applicationContext) { ApplicationUtil.applicationContext = applicationContext; } /** * 获取静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } /** * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } /** * 清除SpringContextHolder中的ApplicationContext为Null. */ public static void clearHolder() { applicationContext = null; } /** * 检查ApplicationContext不为空. */ private static void assertContextInjected() { // if (applicationContext == null) { // throw new IllegalStateException( // "applicaitonContext未注入,请在applicationContext.xml中定义本SpringUtil--------<bean class='xxxx.SpringUtil' />"); // } Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringUtil."); } }