zoukankan      html  css  js  c++  java
  • 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

    ----------------------------------- 作者:怒吼的萝卜 链接:http://www.cnblogs.com/nhdlb/ -----------------------------------
  • 相关阅读:
    课堂例子验证
    大道至简第三章读后感
    动手动脑例子验证
    各数相加的思路、流程图、源代码及实现截图
    大道至简第二章读后感
    《大道至简》第一章读后感
    个人冲刺08
    个人冲刺07
    构建之法读后感04
    个人冲刺06
  • 原文地址:https://www.cnblogs.com/nhdlb/p/15660386.html
Copyright © 2011-2022 走看看