专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

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

文章永久链接:https://tech.souyunku.com/48418

未经允许不得转载:搜云库技术团队 » SpringBoot项目中调用第三方jar包中的类时报错 — 没有注入类的2种解决方法

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们