我必须在MyException类中访问ApplicationContext
public class MyException extends Exception {
public MyException(Map<String, Map<String,String>> errorObj) throws IOException {
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
Environment env = applicationContext.getEnvironment();
...
}
}
此服务将其抛出。
@Service
public class MyServiceImpl implements MyService {
@Override
public Response myFunction() {
throw new MyException(errorObj);
...
}
}
编辑为ApplicationContextProvider
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
public static ApplicationContext getApplicationContext(){
return context;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}
当我运行unittest时,我在ApplicationContext上收到了NullPointerException。我想模拟ApplicationContext怎么做?
我仅在单元测试中发现了此错误,但是当我使用spring-boot运行时,它运行正常