Search code examples
javaspringcontrollers

Spring - separate directory for controllers


I'm a newbie in Spring and have one question about inserting all controllers in another directory than an executable spring boot file.

This tutorial

I have to have GreetingController.java and Application.java in one directory because if not, then I can't run mvn spring:boot-run

Is there a way to have Application.java in /java directory and all controllers in /java/controllers? Can I create some config file to inform Application.java where all the files are?

Thank you


Solution

  • I am little bit confused. But first point - It is good to have all controllers in separate directory, it is best practise, but better is using /rest directory. Second point - You have to define application context and enable few things (for example via annotation). Try to look here http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html, here you can see annotations and basic structure. For you, set this annotations to your Application.java:

    @Configuration
    @EnableAutoConfiguration
    @ComponentScan
    

    More information and where to write it you can find in link what I posted. If you configure application context and you set EnableAutoconfiguration and ComponentScan, Spring will look up for all annotated components and your controllers (if you annotated you controller class by @Controller annotation.