【问题标题】:Execute method after jHipster application startedjHipster 应用程序启动后的执行方法
【发布时间】:2017-10-09 19:28:47
【问题描述】:

我想在 jHipster 应用程序启动后执行一个方法。我应该把我的方法放在哪里? 我尝试在MyApp.java 方法中运行我的方法:

    @PostConstruct
    public void initApplication()

但我得到了错误:

 Invocation of init method failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxx.xxx.xxx
xxx.xxx.xxx.cars, could not initialize proxy - no Session

【问题讨论】:

    标签: java jhipster


    【解决方案1】:

    您应该定义一个单独的类,使用 @Service@Component@Configuration 进行注释,具体取决于您要实现的目标,并将初始化数据所需的 JPA 存储库注入此类。

    这个类也可以实现ApplicationRunner interface

    或者,您可以考虑使用 Liquibase 迁移从 CSV 文件加载数据,请参阅src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xmlusers.csv 示例

    【讨论】:

      【解决方案2】:

      你有两个选择。

      第一个选项:让你的主类实现 CommandLineRunner。

      public class MyJhipsterApp implements CommandLineRunner{
         public static void main(String[] args) throws UnknownHostException {
           //jhipster codes ...
        }
      
          //method implemented from CommandLineRunner
          @Override
          public void run(String... strings) throws Exception {
              log.info("hello world, I have just started up");
          }
      }
      

      第二个选项:创建一个配置文件并监听 ApplicationReadyEvent 来触发你的方法。

      @Configuration
      public class ProjectConfiguration {
          private static final Logger log = 
         LoggerFactory.getLogger(ProjectConfiguration.class);
      
         @EventListener(ApplicationReadyEvent.class)
         public void doSomethingAfterStartup() {
          log.info("hello world, I have just started up");
        }
      }
      

      就个人而言,我更喜欢第二个。

      【讨论】:

      • @EventListener(ApplicationReadyEvent.class) 为我工作,谢谢
      【解决方案3】:

      Jhipster 基于 SpringBoot 作为后端,因此解决方案可能是在 SpringBoot 配置主文件中添加该方法,如此链接所述:stack overflow question

      以防万一解决方案被删除,这里是代码:

      @Configuration
      @EnableAutoConfiguration
      @ComponentScan
      public class Application extends SpringBootServletInitializer {
      
          @SuppressWarnings("resource")
          public static void main(final String[] args) {
              ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
      
              context.getBean(Table.class).fillWithTestdata(); // <-- here
          }
      }
      

      如果你不希望它被阻塞,你可以用 @Async 注释你正在调用的方法。

      希望这会有所帮助!不要犹豫,询问更多详情。

      【讨论】:

      • 我尝试了您的解决方案,但仍然出现同样的错误。
      • 也许如果您编辑您的问题并添加更多详细信息,我将能够提供帮助。 @gaelmarziou 的回答对你有帮助吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多