首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >弹簧应用稀缺性

弹簧应用稀缺性
EN

Stack Overflow用户
提问于 2017-01-30 22:52:30
回答 1查看 38关注 0票数 0

我正在尝试在应用程序启动期间初始化一些bean,这些bean将从静态共享内存结构中读取。我以前使用过@PostContruct,但想转移到一个更基于事件的初始化,这样我就可以使用Spring特性(Config、Resources等)。避免重复自己。

所有数据bean都实现了这个接口:

代码语言:javascript
复制
public interface DataInterface {
    public void loadData();

    public List<String> getResults(String input);
}

我尝试过实现ServletContextListenerWebApplicationInitializer接口,但似乎都没有被调用。

代码语言:javascript
复制
@Service
public class AppInit implements WebApplicationInitializer {
    @Autowired
    DataInterface[] dataInterfaces;

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // This does not get called
        for (DataInterface interface : dataInterfaces)
            interface.loadData();
    }
}


@WebListener
public class AppContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // does not get called
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // does not get called
    }
}

我还可以尝试在main()函数的末尾初始化这些类,该函数在启动SpringApplication后返回。

代码语言:javascript
复制
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        // Can I initialize the DataInterfaces here???
    }
}

看来应该有更好的办法。

编辑:

最后我使用了以下解决方案,因为我无法接收春季医生中列出的任何春季医生事件。

代码语言:javascript
复制
@Component
public class DalInitializer implements ApplicationListener {
    @Autowired
    DataInterface[] dataInterfaces;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent.getClass() == ApplicationReadyEvent.class) {
            for (DataInterface interface : dataInterfaces)
                interface.loadData();
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-30 23:05:18

使用spring应用程序事件侦听器,请参阅Spring框架中更好的应用程序事件

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41946852

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档