spring boot无法自动注入bean?原因在这儿

Description:

Field helloSpringBootService in com.zd.hellospringboot.HelloController required a bean of type 'com.zd.service.HelloSpringBootService' that could not be found.


Action:

Consider defining a bean of type 'com.zd.service.HelloSpringBootService' in your configuration.

这段话的大致意思为:在com.zd.hellospringboot helloSpringBootService.HelloController需要一个com.zd.service类型的bean。无法找到HelloSpringBootService;

我的项目结构为:

APP 类的代码为:

package com.zd.hellospringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 *
 */
// 此注解指定这是一个SpringBoot的应用程序,不加就会报异常 Unable to start
// ServletWebServerApplicationContext due to missing ServletWebServerFactory
// bean
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		// SpringApplication用于从main方法中启动Spring应用的类
		SpringApplication.run(App.class, args);
	}
}

controller类的代码为:

package com.zd.hellospringboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zd.service.HelloSpringBootService;

//RestController相当于SpringMVC中的 @Controller + @ResponseBody
@RestController
public class HelloController {

	@Autowired
	private HelloSpringBootService helloSpringBootService;

	// 映射"/hello"请求
	@RequestMapping("/hello3")
	public String hello3() {
		return helloSpringBootService.sayHelloWord();
	}
}

service代码为:

package com.zd.service;

public interface HelloSpringBootService {

	public String sayHelloWord();
}

serviceImpl代码为:

package com.zd.serviceimpl;

import org.springframework.stereotype.Service;

import com.zd.service.HelloSpringBootService;

@Service("helloSpringBootService")
public class HelloSpringBootImpl implements HelloSpringBootService {

	@Override
	public String sayHelloWord() {
		String str = "这里是springBoot实现类中的方法!";
		return str;
	}

}

代码没有什么问题,但是在这种项目结构下运行报错为:


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-09-04 11:02:22.144  INFO 14200 --- [           main] com.zd.hellospringboot.App               : Starting App on zdAdmin with PID 14200 (D:\workspace\helloSpringBoot\target\classes started by zdAdmin in D:\workspace\helloSpringBoot)
2018-09-04 11:02:22.147  INFO 14200 --- [           main] com.zd.hellospringboot.App               : No active profile set, falling back to default profiles: default
2018-09-04 11:02:22.192  INFO 14200 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2ea6137: startup date [Tue Sep 04 11:02:22 CST 2018]; root of context hierarchy
2018-09-04 11:02:22.993  INFO 14200 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-09-04 11:02:23.013  INFO 14200 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-09-04 11:02:23.013  INFO 14200 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-09-04 11:02:23.018  INFO 14200 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_172\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_172/bin/server;C:/Program Files/Java/jre1.8.0_172/bin;C:/Program Files/Java/jre1.8.0_172/lib/amd64;D:\app\zdAdmin\product\11.2.0\client_1\bin;F:\app\zdAdmin\product\11.2.0\client_1\bin;E:\app\zdAdmin\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Java\jdk1.8.0_172\bin;E:\Program Files\VisualSVN Server\bin;E:\Program Files\TortoiseSVN\bin;E:\tools\apache-maven-3.5.3\bin;E:\ue;D:\app\zdAdmin\product\11.2.0\client_1\BIN;E:\app\zdAdmin\product\11.2.0\dbhome_1\BIN;C:\Users\zdAdmin\AppData\Local\Microsoft\WindowsApps;;E:\开发软件\eclipse;;.]
2018-09-04 11:02:23.110  INFO 14200 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-09-04 11:02:23.110  INFO 14200 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 927 ms
2018-09-04 11:02:23.213  INFO 14200 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-09-04 11:02:23.213  INFO 14200 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-09-04 11:02:23.213  INFO 14200 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-09-04 11:02:23.213  INFO 14200 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-09-04 11:02:23.213  INFO 14200 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-09-04 11:02:23.256  WARN 14200 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloController': Unsatisfied dependency expressed through field 'helloSpringBootService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zd.service.HelloSpringBootService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-09-04 11:02:23.258  INFO 14200 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-09-04 11:02:23.270  INFO 14200 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-04 11:02:23.348 ERROR 14200 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field helloSpringBootService in com.zd.hellospringboot.HelloController required a bean of type 'com.zd.service.HelloSpringBootService' that could not be found.


Action:

Consider defining a bean of type 'com.zd.service.HelloSpringBootService' in your configuration.

解决办法:

根据英文提示报错原因是在配置中找不到指定的自动注入类型bean;

去网上查找相关问题,原因如下:

SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描! 
“Application类”是指SpringBoot项目入口类。这个类的位置很关键: 
如果Application类所在的包为:com.boot.app,则只会扫描com.boot.app包及其所有子包,如果service或dao所在包不在com.boot.app及其子包下,则不会被扫描!
即, 把Application类放到dao、service所在包的上级,com.boot.Application 
知道这一点非常关键,不知道Spring文档里有没有给出说明,如果不知道还真是无从解决。

也就是说我这里报错是因为APP类(SpringBoot项目入口类)所在的包的子包和APP类不在同一个父包下面,所以会报错;因此我修改service及serviceImpl所在包的包名为:

原先的是这样的:

修改完成后启动项目:


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-09-04 11:26:34.094  INFO 12536 --- [           main] com.zd.hellospringboot.App               : Starting App on zdAdmin with PID 12536 (D:\workspace\helloSpringBoot\target\classes started by zdAdmin in D:\workspace\helloSpringBoot)
2018-09-04 11:26:34.098  INFO 12536 --- [           main] com.zd.hellospringboot.App               : No active profile set, falling back to default profiles: default
2018-09-04 11:26:34.134  INFO 12536 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@52e677af: startup date [Tue Sep 04 11:26:34 CST 2018]; root of context hierarchy
2018-09-04 11:26:34.969  INFO 12536 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-09-04 11:26:34.985  INFO 12536 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-09-04 11:26:34.985  INFO 12536 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-09-04 11:26:34.985  INFO 12536 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_172\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_172/bin/server;C:/Program Files/Java/jre1.8.0_172/bin;C:/Program Files/Java/jre1.8.0_172/lib/amd64;D:\app\zdAdmin\product\11.2.0\client_1\bin;F:\app\zdAdmin\product\11.2.0\client_1\bin;E:\app\zdAdmin\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Java\jdk1.8.0_172\bin;E:\Program Files\VisualSVN Server\bin;E:\Program Files\TortoiseSVN\bin;E:\tools\apache-maven-3.5.3\bin;E:\ue;D:\app\zdAdmin\product\11.2.0\client_1\BIN;E:\app\zdAdmin\product\11.2.0\dbhome_1\BIN;C:\Users\zdAdmin\AppData\Local\Microsoft\WindowsApps;;E:\开发软件\eclipse;;.]
2018-09-04 11:26:35.086  INFO 12536 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-09-04 11:26:35.087  INFO 12536 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 968 ms
2018-09-04 11:26:35.203  INFO 12536 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-09-04 11:26:35.208  INFO 12536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-09-04 11:26:35.208  INFO 12536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-09-04 11:26:35.209  INFO 12536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-09-04 11:26:35.209  INFO 12536 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-09-04 11:26:35.495  INFO 12536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@52e677af: startup date [Tue Sep 04 11:26:34 CST 2018]; root of context hierarchy
2018-09-04 11:26:35.542  INFO 12536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello2]}" onto public java.lang.String com.zd.hellospringboot.HelloController.hello2()
2018-09-04 11:26:35.542  INFO 12536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String com.zd.hellospringboot.HelloController.hello()
2018-09-04 11:26:35.542  INFO 12536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello3]}" onto public java.lang.String com.zd.hellospringboot.HelloController.hello3()
2018-09-04 11:26:35.542  INFO 12536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-09-04 11:26:35.542  INFO 12536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-09-04 11:26:35.574  INFO 12536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-04 11:26:35.574  INFO 12536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-04 11:26:35.605  INFO 12536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-04 11:26:35.742  INFO 12536 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-09-04 11:26:35.761  INFO 12536 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-09-04 11:26:35.776  INFO 12536 --- [           main] com.zd.hellospringboot.App               : Started App in 1.948 seconds (JVM running for 2.652)

没有再报错,去浏览器访问,成功执行:

 

展开阅读全文

没有更多推荐了,返回首页