该类须在spring容器中注入。
@Component
public class BeanFactory implements ApplicationContextAware {
private static ApplicationContext context;
private BeanFactory() {
}
public static <T> T getBean(String name, Class<T> type) {
T t = context.getBean(name, type);
if (t != null)
return t;
return context.getBean(type);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) context.getBean(name);
}
public static void setContext(ApplicationContext applicationContext) {
if (context == null) {
synchronized (BeanFactory.class) {
if (context == null) {
context = applicationContext;
}
}
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if (context == null) {
synchronized (BeanFactory.class) {
if (context == null) {
context = applicationContext;
}
}
}
}
}