consider defining a bean of type 'Mapper' in your configuration

Viewed 3213

I'm making SpringBoot Project and following some instructions for testing Spring Boot.

While I tried to connect mysql DB with project, service cannot find the mapper.

i don't know why it cannot find the mapper...

@Service
public class TestService {
    
    @Autowired
    TestMapper mapper;
    
    public List<TestVo> selectTest(){
        return mapper.selectTest();
    }
}

this is the service code and

@Repository
@Mapper
public interface TestMapper {
    List<TestVo> selectTest();
}

this is the mapper code

the following error is

Field mapper in com.steve.firstBoot.test.service.TestService required a bean of type 'com.steve.firstBoot.test.mapper.TestMapper' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.steve.firstBoot.test.mapper.TestMapper' in your configuration.

I will post the image of my packages setting...

enter image description here

2 Answers

Spring can not create an object for the interface. Make sure there should be an implementation class of every interface that needs to be autowired.

After this people generally follow 2 approaches.

1.Mark the interface with @Repository/@Service based on functionality and all its implementation class with @Component

2.Can directly mark implementation class with @Repository/@Service without even marking interface.

Any of them is fine.

  1. Make a class that implements your interface and annotate it with one of the bean stereotype annotations, i.e @Component, @Service, @Repository
  2. Remove the @Repository annotation from your interface
Related