简体   繁体   中英

Bean of Interface type could not be found

first of all I would like to say that I've read simmilar questions and implemented thier answers, but nothing seems to work. TL;DR I'm implementing an example from a book "Spring" and here's my problem. A starting class:

package com.example.demo;
@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.demo.dao", "com.example.demo.model", "com.example.demo.service"})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

A Controller class:

package com.example.demo.api;
@Controller
@RequestMapping("/spittles")
public class SpittleController {
    private SpittleRepository a;
    @Autowired
    public SpittleController(@Qualifier("abc") SpittleRepository a){
        this.a = a;
    }
}

Interface:

package com.example.demo.dao;
@Repository("abc")
public interface SpittleRepository {
    List<Spittle> findSpittles(long max, int count);
}

My Output:

Description:
Parameter 0 of constructor in com.example.demo.api.SpittleController required a bean of type 'com.example.demo.dao.SpittleRepository' that could not be found.
The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Qualifier(value="abc")

As I said before, the example is literally copied from the book (I simplified it for the purpose of the question). The only situation where this program does not throw an error is when I add the annotation: @ComponentScan("com.example.demo.dao") to the DemoApplication class (but works only if there is one file inside dao). Alternatively, when I replace the interface keyword with a class keyword, it also works.

Is there any way to make the class (DemoApplication) to find this interface?

package com.example.demo.dao;
@Repository
public interface SpittleRepository {
    List<Spittle> findSpittles(long max, int count);
}

package com.example.demo.api;
@Controller
@RequestMapping("/spittles")
public class SpittleController {
    private SpittleRepository a;
    @Autowired
    public SpittleController(@Qualifier("spittleRepository ") SpittleRepository a){
        this.a = a;
    }
}
  1. @SpringBootApplication will do a component scan for all packages under com.example.demo , so it is not required to explicitly mention the base packages.
  2. Create a repository class and implement the interface SpittleRepository and anotate the new class with @Component . An implementation for the interface is required here.

The annotation @Repository should be used on a class, but not an interface. Just look at this @Repository

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM