1. 程式人生 > >spring boot無法自動注入bean?原因在這兒

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.ser[email protected]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.ser[email protected]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.ser[email protected]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)

沒有再報錯,去瀏覽器訪問,成功執行: