java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot无法扫描Bean

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

作者:懵懂学子

这篇文章主要介绍了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类要扫描哪些包下的注解。

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

您可能感兴趣的文章:
阅读全文