Spring @ComponentScan for @Service

I have a package named com.example.service

and in my Spring config class I have an annotation @ComponentScan({"com.example.service"},{"com.example.controller"})

.

When I try to execute the @Autowire

service, the code is not compiled with NoSuchBeanDefinitionException

. The MyService interface is annotated with @Service

.

I am currently using a rather ugly workaround and declare each service bean in my ExampleConfig.java example as

@Bean
public MyService myService() {
    return new MyServiceImpl();
}

      

Generally, it works @ComponentScan

, if I remove the controller package, the controllers will not be found. What did I get wrong? Please let me know if I have missed any relevant information.

+3


source to share


2 answers


MyService interface is annotated with @Service



You need to annotate the implementation of your interface. Not the interface itself.

+3


source


Try using the below ComponentScan

annotation code to scan multiple packages:

@ComponentScan({"com.example.service","com.example.controller"})

      

instead



@ComponentScan({"com.example.service"},{"com.example.controller"})

      

@ComponentScan uses a string array to scan multiple basic packages.

0


source







All Articles