Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller / RestController from Spring Gradle library

I want to use a Controller from a Gradle Library that I wrote but it does not get Autowired in the application where I use the library.

It does work when I use @Import(ControllerName.class) on the ApplicationClass of the running application but then I would have to manually import every single class from the library

@ComponentScan doesn't work and from what I read it doesn't work with @Controller and @RestController anyway only with @Bean, @Service and @Component.

This is the controller-class in the library (I left out the business logic)

@Controller
public class FrontendController {


    @GetMapping("/login")
    public String showLoginForm(){
        return "login";
    }

    //some other endpoints
}

And this is currently the applicationClass in my main application:

@SpringBootApplication
@ComponentScan(basePackages = {"com.myapp.demo", "com.myapp.login-lib"})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
like image 844
Juliette Avatar asked Nov 25 '25 04:11

Juliette


1 Answers

I found my error. In my library I (obviously) don't need a Class with a public static void main but what I do need to correctly autowire stuff from my library is a class with @Configuration.

Since I also have repositories and entities I also need to define their packages within the library -> so I added a class to the library that looks as follows:

@Configuration
@ComponentScan(basePackages = {"com.myapp.login-lib"})
@EnableJpaRepositories(basePackages = {"com.myapp.login-lib"})
@EntityScan(basePackages = {"com.myapp.login-lib"})
public class BaseConfiguration {
}

Then in the application where I use the library I only needed to import that configuration:

import com.myapp.login-lib.BaseConfiguration;

@SpringBootApplication
@Import(BaseConfiguration.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
like image 157
Juliette Avatar answered Nov 27 '25 18:11

Juliette