Search code examples
javaspringspring-bootcomponent-scan

After adding @ComponentScan to load beans from a jar my controllers isn't scan and i get 404


I have a spring-boot application (Java8, spring-boot 2.1.4-RELEASE).

One of the services in the business layer need to @Autowire a bean from a certain jars in my classpath. In order to achieve that i had to add @ComponentScan({"package.to.my.bean.inside.the.jar"}) and it was magically scanned and wired successfully (this was added to the main spring-boot class which declare the main method).

However, since then my controllers aren't scanned hence the DispatcherServlet is returning 404 for every request i trigger (default dispatcher). Actually my entire spring-boot app annotations is being ignored - no scan is performed. Just to emphasis - the application worked perfectly before adding the @ComponentScan.

Main spring-boot app class:

package com.liav.ezer;

// This is the problematic addition that cause the endpoints to stop
// inside a jar in the classpath, in com.internal.jar package resides an 
// object which i need to wire at run time
@ComponentScan({"com.internal.jar"})
@SpringBootApplication
public class JobsApplication {
    public static void main(String[] args) {
        SpringApplication.run(JobsApplication .class, args);
        }
}

Controller example:

package com.liav.ezer.controller;

@RestController
@EnableAutoConfiguration
@RequestMapping(path = "/jobs")
public class JobController {

    @GetMapping(path="/create", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    String createJob(@RequestParam() String jobName) String jobName){       
        return "job created...";
    }
}

I tried adding my spring-boot app base package to the list of packages in the @ComponentScan with no luck. I tried narrowing down the scope of the package declaration to be only on the class which i need with no luck. Here is the code


Solution

  • If so, remove @ComponentScan, can declare that bean in yourself configuration. try below

    @SpringBootApplication
    public class JobsApplication {
        public static void main(String[] args) {
            SpringApplication.run(JobsApplication .class, args);
            }
         @Bean
         public BeanInOtherJar xxBean(){
            return new com.internal.jar.XXX();
         }
    }