访问启动上的春季应用程序上下文

发布于 01-19 13:26 字数 1001 浏览 3 评论 0原文

我正在将一个项目迁移到 Spring Boot,但在使用旧数据库存储库时遇到一些问题。旧项目构建为在 Tomcat 上运行的 WAR,使用 persistence.xml 和 context.xml 来配置数据库。旧的存储库是从不同的地方以静态方式访问的,这使得将它们迁移到 Spring 存储库非常困难。我的问题是,现在不可能迁移旧存储库,因为所有服务也需要迁移等。

我尝试过的一种方法是初始化 LocalContainerEntityManagerFactoryBean,然后我可以使用 application.yml 进行数据库配置。我还可以访问旧类的这个 bean 并检索 EntityManagerFactory。也许这不是最好的方法。我发现了一些关于此的讨论。

public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

...

LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
            
SpringApplicationContext.getBean(LocalContainerEntityManagerFactoryBean.class);
EntityManagerFactory emf = localContainerEntityManagerFactoryBean.getObject();

如果应用程序已启动,则此方法有效。我的问题是我需要在启动时运行一些需要 EntityManagerFactory 的方法。我尝试运行

@PostConstruct
public void init() {

但没有成功,因为应用程序上下文为空。所以我的问题是如何在启动后运行我的方法来访问应用程序上下文?我的应用程序现在扩展了 SpringBootServletInitializer,因此我们仍然可以将其部署为 WAR。

I'm migrating a project to Spring Boot and I'm having some trouble with using the old database repositories. The old project was built as a WAR running on Tomcat, using persistence.xml with context.xml for the configuration of the database. The old repositories was accessed in a static way from various places which makes it really difficult to migrate them to Spring repositories. My problem is that it isn't possible right now to migrate the old repositories because all the services also need to be migrated etc.

One way I have tried is to initialize a LocalContainerEntityManagerFactoryBean then I can use application.yml for the DB configuration. I can also access this bean for the old classes and retrieve an EntityManagerFactory. Maybe it isn't the best approach. I have found some discussions about this.

public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

...

LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
            
SpringApplicationContext.getBean(LocalContainerEntityManagerFactoryBean.class);
EntityManagerFactory emf = localContainerEntityManagerFactoryBean.getObject();

This approach works if the application has started. My problem is I need to run some methods on startup which needs an EntityManagerFactory. I have tried to run

@PostConstruct
public void init() {

with no luck because the application context is null. So my question is how can I run my method after startup where I can access the application context? My application extends SpringBootServletInitializer for now so we can still deploy it as a WAR.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文