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();
    }
}
相關文章
相關標籤/搜索