【问题标题】:Calling a Spring @Service on web application initialization在 Web 应用程序初始化时调用 Spring @Service
【发布时间】:2017-01-10 01:16:53
【问题描述】:

我有一个 web 应用程序,只要我将 .war 放入 Tomcat webapp 文件夹,就需要初始化一些静态变量。此初始化需要调用 @Service 来检索初始设置。

我意识到@Autowire 注入仅在我的 GUI 调用服务时才有效

在应用容器中抛出 .war 后,初始化 Spring Web 应用程序的最佳方法是什么?我需要这个初始化只执行一次。

【问题讨论】:

  • @PostConstruct on init 方法可能会对您有所帮助
  • @JekinKalariya 但是使用 PostConstruct 我需要将我的初始化程序与我的 bean 联系起来......我的初始化程序独立于我的应用程序中的任何业务或组件......我只需要像一个“主”方法将执行一次,并将用数据填充一些变量(如服务器路径等)
  • @amicoderozer 感谢您的链接...检查..

标签: spring web initialization initializer


【解决方案1】:

如果你需要在 servletContext 初始化后做一些事情,在 spring 中,我们使用 ApplicationListener 来做这件事。

public class SpringListener implements ApplicationListener<ContextRefreshedEvent>{

        // this should work if other setting is right  
        @Autowired
        XXX xxx;

        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
                 // do things here
        }
    }

in application.xml
<bean id="eventListenerBean" class="package.name.SpringListener " />

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#context-functionality-events

另一方面,仅供参考,传统方法是使用 ServletContextListener 来完成。 http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html

【讨论】:

  • 嗯,这似乎是一个好方法,因为我不希望我的初始化程序与我的任何 bean 绑定......而且我不想为此创建一个 @entity/repository/service.. . 我的初始化程序唯一要做的就是在类路径中获取@Entities 的.class 并存储在一个静态变量中(因为以后的屏幕将使用这些.classes 自动生成)
  • 很高兴它对您有所帮助。有时 contextRefreshedEvent 调用了两次,因为配置错误,这里是解决方案。 stackoverflow.com/questions/6164573/…
  • 以备不时之需。 :)
猜你喜欢
  • 2013-06-16
  • 2012-05-03
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 2015-03-06
  • 2011-01-23
  • 1970-01-01
  • 2013-07-02
相关资源
最近更新 更多