[英]Why InitializingBean's method wont be called in a normal Java File
Let's say in my java class I have 让我们说我的java课程
class myClass{
public static void main ..{
Validator validator;
LocalValidatorFactoryBean localValidatorFactory = new LocalValidatorFactoryBean();
validator = localValidatorFactory.getValidator();
}
On the last line I get nullPointerException. 在最后一行,我得到nullPointerException。 That is because in my localValidatorFactory, ValidatorFactory
attribute is null and I guess that is responsible to get me the validator. 那是因为在我的localValidatorFactory中, ValidatorFactory
属性为null,我想这有责任让我得到验证器。
Now, my question is that if this was a dynamic webproject and I had a context file, wherein I had defined all these classes, then in that case it would work. 现在,我的问题是,如果这是一个动态的webproject并且我有一个上下文文件,其中我已经定义了所有这些类,那么在这种情况下它将起作用。 Because in that case the afterPropertiesSet
method is called that sets the properties, I guess. 因为在这种情况下调用afterPropertiesSet
方法来设置属性,我想。
But why is it not working in this case? 但是为什么在这种情况下不起作用呢? And what can I do to make it work? 我能做些什么才能让它发挥作用?
Is it that, I should have contextFile, that has all this thing, and in my java file, I do ApplicationContext.getBean()
and after such steps, it will work? 是这样的,我应该有contextFile,它有所有这一切,在我的java文件中,我做ApplicationContext.getBean()
并在这些步骤之后,它会工作吗? Does it mean that initializingBean will work only when things are done like this? 这是否意味着initializingBean只有在这样的事情发生时才会起作用? In normal java code, I can not make initializingBean work? 在普通的java代码中,我无法使initializingBean工作?
InitializingBean
and FactoryBean
(ie LocalValidatorFactoryBean
) are callback interfaces of the spring framework but your code is not using it. InitializingBean
和FactoryBean
(即LocalValidatorFactoryBean
)是spring框架的回调接口,但是您的代码没有使用它。
LocalValidatorFactoryBean
may define dependencies to be autowired (ie resolved and injected) by the container but you create the instance yourself so there is no way for Spring to be involved and process those callbacks properly. LocalValidatorFactoryBean
可以定义容器自动装配(即解析和注入)的依赖关系,但是您自己创建实例,因此Spring无法参与并正确处理这些回调。
You could make all this work propperly in "normal java code" but calling the setter of the factory bean and afterPropertiesSet
yourself. 您可以在“普通的Java代码”中正确地完成所有这些工作,但是自己调用工厂bean和afterPropertiesSet
的setter。 In that case, you're basically doing what Spring does automatically for you when LocalValidatorFactoryBean
is a Spring managed bean. 在这种情况下,当LocalValidatorFactoryBean
是Spring托管bean时,你基本上就是在做Spring自动为你做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.