Spring Boot auto scan

When Spring Boot and Mybatis are integrated, Spring Boot cannot scan the annotations under packages other than the Application class when scanning the annotations, as shown in the following figure:

App is the Application class, and the following figure is the ProductMapper class:

@Mapper
public interface ProductMapper {
    
    @Insert("insert into products (pname,type,price)values(#{pname},#{type},#{price}")
    public int add(Product product);
    
    @Delete("delete from products where id=#{arg1}")
    public int deleteById(int id);
    
    @Update("update products set pname=#{pname},type=#{type},price=#{price} where id=#{id}")
    public int update(Product product);
    
    @Select("select * from products where id=#[arg1}")
    public Product getById(int id);
    
    @Select("select * from productsorder by id desc")
    public List<Product> queryByLists();
}

 

When the App class runs, the background will report that the ProductMapper class bean is not found:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException:<br> No qualifying bean of type 'com.self.spring.mapper.ProductMapper' available

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353)

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)

    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1090)

    at com.self.spring.springboot.App.main(App.java:17)


The reason for the above error: The default rule of Bean assembly of SpringBoot project is to scan from top to bottom according to the package location where the Application class is located! "Application class" refers to the SpringBoot project entry class. The location of this class is critical: 

If the package where the Application class is located is: io.github.gefangshuai.app, only the io.github.gefangshuai.apppackage and all its sub-packages will be scanned. If the package where the service or dao is located is not under io.github.gefangshuai.appits sub-package, it will not be scanned!

 

Solution

The first type: the Application class is placed under the parent package, and all annotated classes are placed under the same or its subpackages

The second: specify the package URL to be scanned and annotated. The solution to the above problem can be annotated on the Application class to scan the class under the mapper interface package.

@SpringBootApplication
@MapperScan(basePackages="com.self.spring.springboot.mapper")
public class App {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        System.out.println(context.getBean(ProductMapper.class));
        context.close();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324444582&siteId=291194637