SpringBoot项目启动时报错信息:
[main] WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext -
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘skillConfigService’: Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘wxName’ available
Description:
A component required a bean named ‘wxName’ that could not be found.
Action:
Consider defining a bean named ‘wxName’ in your configuration.
大意:spring在创建名称’skillConfigService’的bean时,在这个类文件中注入资源依赖项失败;异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为“wxName”的bean可用。要么定义一个@Component注解的bean,要么在配置文件里配置一个bean。
环境说明:
在第三方a.jar包中,有个@Configuration注解的类:
package com.tx.wx
@Configuration
public class TXApp{
@Bean(name = "wxName")
@SuppressWarnings({ "rawtypes", "unchecked" })
public WXTemplate wxinit(){
.....
}
}
在当前springboot项目中引用a.jar包。其中一个类:
package com.app.user
@Slf4j
@Service
public class SkillConfigService{
@SuppressWarnings("rawtypes")
@Resource(name = "wxName")
private WXTemplate wxName;
}
问题:
包名不同,出现错误。包名相同,正常运行。@Resource只能在同包名下查找?
你的问题在于Spring并不会扫描到jar包的bean,即你在第三方jar包内部的一切配置理论上都不会被Spring管理的,包名相同能扫描原因是Spring扫描默认就是根据包名来的,不写默认其实就是当前主类的包名,你第三方jar包名跟主类相同,就能被Spring扫到,但在jar包内部写Spring的配置注解是非常不推荐的,定制性太强,还很有可能发送像题主这样的冲突(其实你这样是一种冲突,使用方很可能就踩坑了,因为你的jar包包名跟使用方一样,如果再出现一样的类名会发生什么?找Bug找哭了要),而且自动化配置的starter都是加了各种@Condition的注解保证不与使用方冲突,而且一般只是初始化非常关键的几个使用类,题主可以参考一下;
总体就是:不要在自己的第三方jar包写Spring的注解配置想被Spring管理,你这样即绑定了使用方必须使用Spring并且配置扫描你的jar包。而且还很危险