No qualifying bean of type xxx' available 的一种解决方法

获取bean

 Class beanClass = Class.forName(event.className);
 FilterEvent filterEvent = (FilterEvent)BeansContext.getWebApplicationContext().getBean(beanClass);

event.className为要获取的类名

1 反复检查类名是否正确    ok

2 检查包扫描配置是否正确  ok

3 检查bean 是否已注册  ok  检查之后确认bean没有问题

@Service
public class GDXMMXExtendEx implements FilterEvent {

    @PostConstruct
    public void init(){
        System.out.println("==============?");
    }

}

4 在代码其他地方获取bean  ok

5 对比能获取到bean 与不能获取到bean 时的差异 发现

beanClass上的classloader 不一致
能获取到bean的classloader 为RestartClassLoader
不能获取到bean的classloader 为AppClassLoader

  查询classloader的区别 发现 devtools 可能会影响classloader

  去掉这个插件 一切正常了

 <!--   <dependencies>-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-devtools</artifactId>-->
<!--            <optional>true</optional>-->
<!--        </dependency>-->
<!--    </dependencies>

补充:20191217

打包的时候将文件屏蔽掉了

我的bean 叫FIAPITestService  下面这个排除刚好排除掉

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>application.yaml</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>ApplicationTest.class</exclude>
<exclude>**/*Test*.class</exclude>
<exclude>**/static/**</exclude>
<exclude>**/**/*.yaml</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

参考:

https://blog.csdn.net/qq_36285899/article/details/82867768

原文地址:https://www.cnblogs.com/wolbo/p/11510351.html