SpringBoot:Springboot項目中調用第三方jar包中的類時報錯--注入類的兩種方式


前言

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

報錯原因:bean沒有注入,引進來的jar包沒有被spring管理,因為類沒有被@Service,@Repository等類注解,如果我們想用@Autowired注入也會報錯

示例:

@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=)}

解決方式(1)

創建配置類使用@Bean注解進行注入類。

@Configuration
public class UserServiceConfig {

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

解決方式(2)

在啟動類加上掃描注解@ComponentScan("/")

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

    public static void main(String[] args)
    {
        SpringApplication.run(UserApplication .class, args);
    }
}

 

文章轉載至:https://www.cnblogs.com/wueryuan/p/12884366.html


免責聲明!

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



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