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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM