问题描述
我正在开发一个spring MVC应用程序。当我尝试在我的控制器类中使用AnnotationConfigApplicationContext时,我收到以下错误。我不知道这句话到底意味着什么。
I am developing a spring MVC application. When I try to use AnnotationConfigApplicationContext in my controller class I am getting the following error. I have no idea what this statement exactly means.
@RequestMapping(value = "/generate", method = RequestMethod.POST)
public ModelAndView generateMappingFile(@ModelAttribute Mapping mapping)
{
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
MappingFileGenerator mfg = ctx.getBean(MappingFileGenerator.class);
}
错误信息 - >
java.lang.IllegalStateException:org.springframework.context.annotation.AnnotationConfigApplicationContext@116b3c0 has not been refreshed yet
有人可以解释一下这里出了什么问题吗?我正在使用Spring 4.0.1 ..我是spring mvc的新手。
Can someone explain me what went wrong here ? I am using Spring 4.0.1.. I am new to spring mvc.
推荐答案
当您创建 ApplicationContext
的新实例时(无论如何)哪种类型)你基本上是在 ApplicationContext
中配置的每个bean的新实例。这是第一次很好,它可能会工作第二次,取决于bean的数量,豆类的类型将崩溃。由于上下文永远不会被破坏(直到应用程序崩溃并重新启动),您将遇到可能的内存问题,性能问题,奇怪的事务性问题等。
When you are creating a new instance of an ApplicationContext
(regardless which type) you are basically creating new instances of each and every bean configured in that ApplicationContext
. That is nice the first time, it might work the second and depending on the amount of beans, the type of beans will crash after that. As the context will never be destroy (until the app crashed and is restarted) you will run into possible memory issues, performance issues, strange transactional problems etc.
一般规则拇指是从不构造 ApplicationContext
的新实例,而是使用依赖注入。
A general rule of thumb is to never construct a new instance of an ApplicationContext
but to use dependency injection instead.
如果你真的想要访问 ApplicationContext
在控制器中输入该类型的字段并放入 @Autowired
就可以了。
If you really want access to the ApplicationContext
put a field of that type in your controller and put @Autowired
on it.
@Controller
public class MyController {
@Autowired
private ApplicationContext ctx;
….
}
然后你可以查找你需要的bean方法。如果您使用 ApplicationContext
作为bean的工厂,这可能很方便。如果您需要的所有豆子都是单身,那么最好只需注入您需要的豆。
Then you can do a lookup for the bean you need in the method. This can be handy if you use the ApplicationContext
as a factory for your beans. If all the beans you need are singletons it is better to simply inject the bean you need.
@Controller
public class MyController {
@Autowired
private MappingFileGenerator mfg ;
….
}
现在Spring将注入 MappingFileGenerator
,它可用于您的方法。无需创建 ApplicationContext的新实例
。
Now Spring will inject the MappingFileGenerator
and it is available for use in your methods. No need to create a new instance of an ApplicationContext
.
更多信息在。
这篇关于AnnotationConfigApplicationContext尚未刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!