Spring Boot自动扫描

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

Spring Boot自动扫描

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();
}
}
上一篇:初识B/S结构编程技术


下一篇:POJ2407–Relatives(欧拉函数)