C语言学习网

如何理解@Resource注入失败问题

发表于:2022-12-08 作者:安全数据网编辑
编辑最后更新 2022年12月08日,如何理解@Resource注入失败问题,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。项目结构front和client是两个不同的服务,f

如何理解@Resource注入失败问题,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

项目结构

front和client是两个不同的服务,front依赖client项目,需要在front中注入client的类

声明类:

import com.bluewhale.infra.client.IRestClient;... ...@Component("defaultWebServiceRequestHandler")public class DefaultWebServiceRequestHandler implements BaseHandler {        protected Logger logger = LoggerFactory.getLogger(this.getClass());        @Resource(name = "seckillClient")        private IRestClient seckillClient;                @Resource(name = "objectMapper")        protected ObjectMapper objectMapper;        @Resource(name = "restMapping")        public Map restMapping;        ... ...}

注解类:

import org.springframework.stereotype.Component;import com.bluewhale.infra.client.IRestClient;import com.bluewhale.infra.client.impl.BaseRestClient;@Component("seckillClient")public class SeckillClient extends BaseRestClient implements IRestClient {        @Override        protected String getServerUrl() {                return "http://etrade-trans-web/json/";        }}

seckillClent实现了IRestClient接口,在DefaultWebServiceRequestHandler 中注入IRestClient,通过@Resource注解找到对应的类。

但在启动front服务器报错

从报错日志可以看出是因为找不到名为"seckillClient"的依赖,注入失败。

从代码中来看,完全可以确定所有配置正常,注解正常

2019-08-19 11:00:59.105  INFO 7376 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@31c7528f: startup date [Mon Aug 19 11:00:59 CST 2019]; root of context hierarchy2019-08-19 11:00:59.294  INFO 7376 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring2019-08-19 11:00:59.326  INFO 7376 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ddfb45d6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::        (v1.5.9.RELEASE)2019-08-19 11:00:59.778  INFO 7376 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:88882019-08-19 11:01:00.856  WARN 7376 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/bluewhale-seckill-front/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect2019-08-19 11:01:00.856  INFO 7376 --- [           main] bluewhale.front.FrontApplication         : No active profile set, falling back to default profiles: default2019-08-19 11:01:00.903  INFO 7376 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5e4fa1da: startup date [Mon Aug 19 11:01:00 CST 2019]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@31c7528f2019-08-19 11:01:01.825  INFO 7376 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=34349be5-556c-35e3-8c99-3121c02e2e062019-08-19 11:01:01.840  INFO 7376 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring2019-08-19 11:01:01.950  INFO 7376 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration' of type [org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration$$EnhancerBySpringCGLIB$$f40de91a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2019-08-19 11:01:02.013  INFO 7376 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ddfb45d6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2019-08-19 11:01:02.231  INFO 7376 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 11002 (http)2019-08-19 11:01:02.247  INFO 7376 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]2019-08-19 11:01:02.247  INFO 7376 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.232019-08-19 11:01:02.372  INFO 7376 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext2019-08-19 11:01:02.372  INFO 7376 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1469 ms2019-08-19 11:01:02.559  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricsFilter' to: [/*]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]2019-08-19 11:01:02.575  INFO 7376 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]2019-08-19 11:01:02.685  WARN 7376 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/front': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontExecuter': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontProcessFactory': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontProcessConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'logoutProcess': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'frontHandlerConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultWebServiceRequestHandler': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'seckillClient' available2019-08-19 11:01:02.685  INFO 7376 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]2019-08-19 11:01:02.700  INFO 7376 --- [           main] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.2019-08-19 11:01:02.794 ERROR 7376 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : ***************************APPLICATION FAILED TO START***************************Description:A component required a bean named 'seckillClient' that could not be found.Action:Consider defining a bean named 'seckillClient' in your configuration.

经过排查及网上查询发现问题所在

因为项目有做业务分离,所以在启动front服务器,加载主程序时SpringBoot会对依赖包进行扫描,因此需要在主程序入口指定扫描的位置,否则有的地方可能会注入失败。

所以需要在front的Application中指定扫描的包

package bluewhale.front;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.context.annotation.ComponentScan;@ComponentScan(basePackages = { "com.bluewhale.infra", "etrade" })@EnableDiscoveryClient@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })public class FrontApplication {        public static void main(String[] args) throws Exception {                SpringApplication.run(FrontApplication.class, args);        }}

Spring Boot项目中的组件扫描

  • 如果你的其他包层次结构位于使用@SpringBootApplication标注主应用程序下方,则隐式组件扫描将自动涵盖。也就是说,不要明确标注@ComponentScan,Spring Boot会自动搜索当前应用主入口目录及其下方子目录。

  • 如果其他包中的bean /组件不在当前主包路径下面,,则应手动使用@ComponentScan 添加

  • 如果使用了@ComponentScan ,那么Spring Boot就全部依赖你的定义,如果定义出错,会出现autowired时出错,报a bean of type that could not be found错误

看完上述内容,你们掌握如何理解@Resource注入失败问题的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

0