2

I want to execute a method after, jHipster application started. Where should I put my method? I tried to run my method in MyApp.java method:

    @PostConstruct
    public void initApplication()

But I got error:

 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
Ice
  • 1,783
  • 4
  • 26
  • 52

3 Answers3

3

You should define a separate class that you annotate either with @Service, @Component or @Configuration depending on what you want to achieve and inject into this class the JPA repository you need to init your data.

This class could also implement ApplicationRunner interface.

Alternatively, you may consider loading data from a CSV file using a Liquibase migration, see src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml andusers.csv for an example

Gaël Marziou
  • 16,028
  • 4
  • 38
  • 49
1

You have two options.

First option : make your main class implements 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");
    }
}

Second option : create a configuration file and listen to ApplicationReadyEvent to fire your method.

@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");
  }
}

Personally, I prefer the second one.

freemanpolys
  • 1,848
  • 20
  • 19
0

Jhipster is based on SpringBoot for the backend so the solution might be to add the method in the SpringBoot configuration main, like described in this link : stack overflow question

Just in case the solution gets deleted, here is the code :

@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
    }
}

You can annotate the method you're calling with @Async if you don't want it to be blocking.

Hope this helps ! Don't hesitate to ask for more details.

Community
  • 1
  • 1
matthieusb
  • 505
  • 1
  • 10
  • 34