定义
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext _context;
@Autowired
@Primary
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
_context = applicationContext;
}
public static ApplicationContext applicationContext() {
return _context;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T)_context.getBean(name);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return _context.getBean(name, requiredType);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> requiredType) throws BeansException {
return _context.getBean(requiredType);
}
}
定义bean
@Service
public class TestService {}
使用
TestService ts = ApplicationContextHelper.getBean(TestService.class);
浙公网安备 33010602011771号