springboot 无法扫描到父类模块中Bean的原因及解决

 更新时间:2021年08月13日 09:24:49   作者:懵懂学子  
这篇文章主要介绍了springboot 无法扫描到父类模块中Bean的原因及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

springboot 无法扫描到父类模块中Bean

现象:

我定义了两个模块 A 和 B 。B模块依赖A模块

A模块中我定义了一个@Component

却发现在B模块中我无法扫描到这个Bean导入注入失败

如何解决

查阅得知,在springboot中的bean扫描是扫描同级目录或者下级目录,也就是不会扫描到依赖包里面的东西。

但是我又想定义公共Bean,该怎么做呢。

解决方案

手动注入 @Bean

如果你定义的是实体类之类的Bean,那么可以在子类中手动Bean

@Bean
Result result(){
 new Result;
}

配置扫描 @ComponentScan

但是如果你定义的Bean是类似于接口的文件,那你使用手动定义的方法就会发现要写很长一段,把所有的方法都定义一下。所以还有另一种方法

@SpringBootApplication
@ComponentScan(basePackages = {"cn.o"})
public class ProxyDataSourceApplication {
 ...main(){
 }
}

如果定义了@ComponentScan扫描路径,注意不要让@Bean多处定义,否则会报重复注入的错误。

spring boot 启动就自动关闭 之 找不到bean

创建的bean

package com.springboot.entity; 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
 
/**
 * Created by ASUS on 2018/3/20.
 */
@Component
@ConfigurationProperties(prefix = "author")
public class AuthorBean {
    private String name;
    private Long age;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void setAge(Long age) {
        this.age = age;
    }
 
    public Long getAge() {
        return age;
    }
}

写的application类

package com.springboot.demo; 
import com.springboot.entity.AuthorBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * Created by ASUS on 2018/3/20.
 */
@RestController
@org.springframework.boot.autoconfigure.SpringBootApplication
 
public class ApplicationDemo {
    @Autowired
    private AuthorBean authorBean;
 
    @RequestMapping("/kkk")
    String index(){
        return "author name ="+authorBean.getName()+"author age="+authorBean.getAge();
    }
 
    public static void main(String[] args) {
        SpringApplication.run(ApplicationDemo.class,args);
    }
}

控制台报错:

2018-03-20 22:22:02.070 INFO 11360 --- [ main] com.springboot.demo.ApplicationDemo : Starting ApplicationDemo on DESKTOP-IV2AEJK with PID 11360 (D:\IDEA\IDEAWorkSpace\SpringBootDemo\target\classes started by ASUS in D:\IDEA\IDEAWorkSpace\SpringBootDemo)
2018-03-20 22:22:02.074 INFO 11360 --- [ main] com.springboot.demo.ApplicationDemo : No active profile set, falling back to default profiles: default
2018-03-20 22:22:02.144 INFO 11360 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3fa980b: startup date [Tue Mar 20 22:22:02 CST 2018]; root of context hierarchy
2018-03-20 22:22:03.453 INFO 11360 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9090 (http)
2018-03-20 22:22:03.462 INFO 11360 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-03-20 22:22:03.463 INFO 11360 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-03-20 22:22:03.557 INFO 11360 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/helloboot] : Initializing Spring embedded WebApplicationContext
2018-03-20 22:22:03.558 INFO 11360 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1416 ms
2018-03-20 22:22:03.704 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-20 22:22:03.708 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-20 22:22:03.741 WARN 11360 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDemo': Unsatisfied dependency expressed through field 'authorBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springboot.entity.AuthorBean' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-03-20 22:22:03.742 INFO 11360 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-03-20 22:22:03.761 INFO 11360 --- [ main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-03-20 22:22:03.858 ERROR 11360 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

***************************
APPLICATION FAILED TO START
***************************
Description:
Field authorBean in com.springboot.demo.ApplicationDemo required a bean of type 'com.springboot.entity.AuthorBean' that could not be found.
Action:
Consider defining a bean of type 'com.springboot.entity.AuthorBean' in your configuration.
Process finished with exit code 1

其中:

意思就是找不到bean,没有注入进去。

解决方法:

@RestController
@org.springframework.boot.autoconfigure.SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.entity"})
public class ApplicationDemo {
    @Autowired
    private AuthorBean authorBean;

加注解

@ComponentScan(basePackages = {"com.springboot.entity"})

原因:

@SpringBootApplication 注解组合了@Configuration @EnableAutoConfiguration,@ComponentScan.

spring boot 会自动扫描@SpringBootApplication 所在类的同级包以及下级包里的Bean ,建议入口类放置在groupid+arctifactId 组合的包名下

以下收集别的解释:

正常情况下加上@Component注解的类会自动被Spring扫描到生成Bean注册到spring容器中,既然他说没找到,也就是该注解被没有被spring识别,问题的核心关键就在application类的注解SpringBootApplication上

这个注解其实相当于下面这一堆注解的效果,其中一个注解就是@Component,在默认情况下只能扫描与控制器在同一个包下以及其子包下的@Component注解,以及能将指定注解的类自动注册为Bean的@Service@Controller和@ Repository,至此明白问题所在,之前我将接口与对应实现类放在了与控制器所在包的同一级目录下,这样的注解自然是无法被识别的

所以有两种解决办法:

1 .将接口与对应的实现类放在与application启动类的同一个目录或者他的子目录下,这样注解可以被扫描到,这是最省事的办法

2 .在指定的application类上加上这么一行注解,手动指定application类要扫描哪些包下的注解。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java中的线程死锁是什么?如何避免?

    Java中的线程死锁是什么?如何避免?

    这篇文章主要介绍了Java中线程死锁的相关资料,以及避免死锁的方法,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2020-09-09
  • java微信支付功能实现源码

    java微信支付功能实现源码

    这篇文章主要给大家介绍了关于java微信支付功能实现源码的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Java后台通过Collections获取list集合中最大数,最小数代码

    Java后台通过Collections获取list集合中最大数,最小数代码

    这篇文章主要介绍了Java后台通过Collections获取list集合中最大数,最小数代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Java Swing中的文本区(JTextArea)实现换行保存到文件的几个方法

    Java Swing中的文本区(JTextArea)实现换行保存到文件的几个方法

    这篇文章主要介绍了Java Swing中的文本区(JTextArea)实现换行保存到文件的几个方法,本文给出了4种方法,需要的朋友可以参考下
    2014-10-10
  • Maven方式构建SpringBoot项目的实现步骤(图文)

    Maven方式构建SpringBoot项目的实现步骤(图文)

    Maven是一个强大的项目管理工具,可以帮助您轻松地构建和管理Spring Boot应用程序,本文主要介绍了Maven方式构建SpringBoot项目的实现步骤,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • JAVA通过HttpURLConnection 上传和下载文件的方法

    JAVA通过HttpURLConnection 上传和下载文件的方法

    这篇文章主要介绍了JAVA通过HttpURLConnection 上传和下载文件的方法,非常具有实用价值,需要的朋友可以参考下
    2017-09-09
  • spring+apollo动态获取yaml格式的配置方式

    spring+apollo动态获取yaml格式的配置方式

    这篇文章主要介绍了spring+apollo动态获取yaml格式的配置方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • Java基础第二篇方法与数据成员

    Java基础第二篇方法与数据成员

    在上一篇文章中介绍了Java基础 从HelloWorld到面向对象,我们初步了解了对象(object)。对象中的数据成员表示对象的状态。对象可以执行方法,表示特定的动作。这篇文章我们进一步深入到对象。了解Java中方法与数据成员的一些细节。
    2021-09-09
  • java稀疏数组的示例代码

    java稀疏数组的示例代码

    这篇文章主要介绍了java稀疏数组,稀疏数组,记录一共有几行几列,有多少个不同值,把具有不同值的元素和行里了及值记录在一个小规模的数组中,从而缩小程序的规模,对java稀疏数组相关知识感兴趣的朋友一起看看吧
    2022-07-07
  • Java中的JetCache 实战

    Java中的JetCache 实战

    这篇文章主要介绍了Java中的JetCache实战,JetCache是一个基于Java的缓存系统封装,提供统一的API和注解来简化缓存的使用,下文更多相关资料需要的小伙伴可以参考一下
    2022-04-04

最新评论