Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 从init方法调用应用程序上下文_Spring - Fatal编程技术网

Spring 从init方法调用应用程序上下文

Spring 从init方法调用应用程序上下文,spring,Spring,我有一个标准的“context holder”bean(比如MyContext),在我的spring配置文件中实现ApplicationContextAware,还有一个用init方法定义的bean 在init方法中,我调用了MyContext.getApplicationContext().get(“something”),但我得到了NullPointerException,因为应用程序上下文尚未设置。bean是一个集成测试 我想问题是我用init方法在bean之后定义了MyContextbe

我有一个标准的“context holder”bean(比如MyContext),在我的spring配置文件中实现
ApplicationContextAware
,还有一个用init方法定义的bean

在init方法中,我调用了
MyContext.getApplicationContext().get(“something”)
,但我得到了
NullPointerException
,因为应用程序上下文尚未设置。bean是一个集成测试

我想问题是我用init方法在bean之后定义了
MyContext
bean。是这样吗?我认为Spring应该足够聪明,首先设置上下文

对于这种情况有什么解决办法吗?我的意思是,当您在使用init方法调用应用程序上下文本身的任何其他bean之后定义了
ApplicationContextAware
bean时


顺便问一下,泉水的流量是多少?我会接受这样的回答:“spring首先加载所有配置,然后创建所有bean实例,满足所有依赖项,调用所有init方法,最后它将应用程序上下文设置为
ApplicationContextAware
bean-因此不能在init方法中使用应用程序上下文。”

您应该使用@PostConstruct。带有此注释的方法将在bean压缩之后但在任何地方使用之前立即调用

@PostConstruct
    public void afterInitMethod() throws Exception {
     //do you things there
    }

是的,Spring提供了一种方法来告诉容器一个bean依赖于另一个bean,因此应该在它之后实例化。一旦指定了依赖项,在
spring.xml
文件中以什么顺序列出
bean
定义就无关紧要了

<bean id="dependentBean" class="com.my.app.DependentBean" depends-on="appContext" />

<bean id="appContext" class="com.my.app.MyContext" />


您可以发布示例代码吗?您不应该使用
ApplicationContext
您应该使用依赖项注入。