zoukankan      html  css  js  c++  java
  • Spring Boot自动扫描

      进行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:

    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项目入口类。这个类的位置很关键:

    如果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();
        }
    }
  • 相关阅读:
    JFinal Web开发学习(二)目录、架构、package设计
    JFinal Web开发学习(一)开启HelloWorld
    使用JFinal实现使用MVC获取表单中的数据并将提示信息返回给另一jsp页面。
    [JSOI2010]满汉全席 -- 2-SAT
    [HNOI/AHOI2018] 道路
    ZJOI2006 物流运输
    HNOI2005 狡猾的商人
    打上标记(给树)
    hdu-6201
    Wannfly day2 采蘑菇
  • 原文地址:https://www.cnblogs.com/javJoker/p/7352818.html
Copyright © 2011-2022 走看看