Spring Boot自动扫描

  进行Spring Boot和Mybatis进行整合的时候,Spring Boot注解扫描的时候没法扫描到Application类的之外的包下面的注解,以下图:html

App就是Application类,下图是ProductMapper 类:java

@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();
}

App类运行的时候后台就会报没有找到ProductMapper 这个类bean:git

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException:
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)

 

形成上面的错误缘由:SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描! “Application类”是指SpringBoot项目入口类。这个类的位置很关键:github

若是Application类所在的包为:io.github.gefangshuai.app,则只会扫描io.github.gefangshuai.app包及其全部子包,若是service或dao所在包不在io.github.gefangshuai.app及其子包下,则不会被扫描!spring

 

解决方法springboot

第一种:Application类放在父包下面,全部有注解的类放在同一个下面或者其子包下面app

第二种:指定要进行扫描注解的包URL,上面的问题的解决方案能够在Application类上面加注解扫描mapper接口包下面的类。spa

@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();
    }
}
相关文章
相关标签/搜索