Spring Boot自动扫描

转自: https://www.cnblogs.com/javJoker/p/7352818.html

 

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

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

复制代码

@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:

1

2

3

4

5

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)

 

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

如果Application类所在的包为:io.github.gefangshuai.app,则只会扫描io.github.gefangshuai.app包及其所有子包,如果service或dao所在包不在io.github.gefangshuai.app及其子包下,则不会被扫描!

 

解决方法

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

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

复制代码

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

复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值