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);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With