欢迎光临
我的个人博客

spring注入静态ApplicationContextAware

首先写一个通用类

package core.support;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringAcaHolder implements ApplicationContextAware {

private static ApplicationContext applicationContext;

public void setApplicationContext(ApplicationContext applicationContext) {
       SpringAcaHolder.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
       checkApplicationContext();
       return applicationContext;
}

@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
       checkApplicationContext();
       return (T) applicationContext.getBean(name);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T getBean(Class<T> clazz) {
       checkApplicationContext();
       Map beanMaps = applicationContext.getBeansOfType(clazz);
       if (beanMaps != null && !beanMaps.isEmpty()) {
              return (T) beanMaps.values().iterator().next();
       } else {
              return null;
       }
}

private static void checkApplicationContext() {
       if (applicationContext == null) {
              throw new IllegalStateException(
              "applicaitonContext未注入,请在applicationContext.xml中定义SpringAcaHolder");
       }
}

}

然后到applicationContext.xml中注入bean

<bean id="springAcaHolder" class="core.support.SpringAcaHolder"  lazy-init="false"  ></bean>

最后在其他类中

SpringBeetlSql beetlsql = SpringAcaHolder.getBean(SpringBeetlSql.class);

转载请标明来源:ibear » spring注入静态ApplicationContextAware

分享到:更多 ()

Where there is a will there is a way

我的新浪微博