springboot項目中調用第三方jar包中的類時報錯 — 沒有注入類的2種解決方法


使用場景:將一些公共的方法封裝成了一個jar包,在其他項目中進行引用的時候報錯

報錯原因:bean沒有注入,引進來的jar包沒有被spring管理

因為這兩個類沒有被@Service,@Repository等類注解,如果我們想用@Autowired注入會報錯

在項目中注入引用的jar包中的UserService類時報錯

@Autowired
public UserService userService;

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.lib.user.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}

報錯原因:bean沒有注入,因為UserService類沒有被@Service,@Repository等類注解,所以我們使用@Autowired注入會報錯

 

解決方法1:可以新建一個UserServiceConfig類,在里面獲得我們想要注入的第三方jar包的類,通過@Configuration注解這個Config類,在方法上注解@Bean,這樣我們在用@Autowired注解注入就可以了

@Configuration
public class UserServiceConfig {

    @Bean
    UserService getUserService(){
        UserService  userService = new UserService();
        return userService;
    }
}

 解決方法2:在主啟動類上加入@ComponentScan("/")

//手動加上@ComponentScan注解並指定那個bean所在的包
//@ComponentScan 的作用就是根據定義的掃描路徑,把符合掃描規則的類裝配到spring容器中
@ComponentScan(basePackages={"com.util.user"}) public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication .class, args); } }


免責聲明!

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



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