1. 程式人生 > >spring boot 啟動就自動關閉 之 找不到bean

spring boot 啟動就自動關閉 之 找不到bean

建立的bean

package com.springboot.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

/**
 * Created by ASUS on 2018/3/20.
 */
@Component
@ConfigurationProperties(prefix = "author")
public class AuthorBean {
    private String name;
    private Long age;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public Long getAge() {
        return age;
    }
}

寫的application類:

package com.springboot.demo;

import com.springboot.entity.AuthorBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by ASUS on 2018/3/20.
 */
@RestController
@org.springframework.boot.autoconfigure.SpringBootApplication

public class ApplicationDemo {
    @Autowired
    private AuthorBean authorBean;

    @RequestMapping("/kkk")
    String index(){
        return "author name ="+authorBean.getName()+"author age="+authorBean.getAge();
    }

    public static void main(String[] args) {
        SpringApplication.run(ApplicationDemo.class,args);
    }
}

控制檯報錯:

2018-03-20 22:22:02.070  INFO 11360 --- [           main] com.springboot.demo.ApplicationDemo      : Starting ApplicationDemo on DESKTOP-IV2AEJK with PID 11360 (D:\IDEA\IDEAWorkSpace\SpringBootDemo\target\classes started by ASUS in D:\IDEA\IDEAWorkSpace\SpringBootDemo)
2018-03-20 22:22:02.074  INFO 11360 --- [           main] com.springboot.demo.ApplicationDemo      : No active profile set, falling back to default profiles: default
2018-03-20 22:22:02.144  INFO 11360 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot
[email protected]
3fa980b: startup date [Tue Mar 20 22:22:02 CST 2018]; root of context hierarchy 2018-03-20 22:22:03.453 INFO 11360 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9090 (http) 2018-03-20 22:22:03.462 INFO 11360 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-03-20 22:22:03.463 INFO 11360 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27 2018-03-20 22:22:03.557 INFO 11360 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/helloboot] : Initializing Spring embedded WebApplicationContext 2018-03-20 22:22:03.558 INFO 11360 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1416 ms 2018-03-20 22:22:03.704 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-03-20 22:22:03.707 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-03-20 22:22:03.708 INFO 11360 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-03-20 22:22:03.741 WARN 11360 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationDemo': Unsatisfied dependency expressed through field 'authorBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springboot.entity.AuthorBean' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2018-03-20 22:22:03.742 INFO 11360 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2018-03-20 22:22:03.761 INFO 11360 --- [ main] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2018-03-20 22:22:03.858 ERROR 11360 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Field authorBean in com.springboot.demo.ApplicationDemo required a bean of type 'com.springboot.entity.AuthorBean' that could not be found. Action: Consider defining a bean of type 'com.springboot.entity.AuthorBean' in your configuration. Process finished with exit code 1
其中:


意思就是找不到bean,沒有注入進去。

解決方法:

@RestController
@org.springframework.boot.autoconfigure.SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.entity"})
public class ApplicationDemo {
    @Autowired
    private AuthorBean authorBean;
加註解 
@ComponentScan(basePackages = {"com.springboot.entity"})

原因:

@SpringBootApplication 註解組合了@Configuration  @EnableAutoConfiguration,@ComponentScan.

spring boot 會自動掃描@SpringBootApplication 所在類的同級包以及下級包裡的Bean ,建議入口類放置在groupid+arctifactId 組合的包名下

以下收集別的解釋:

正常情況下加上@Component註解的類會自動被Spring掃描到生成Bean註冊到spring容器中,既然他說沒找到,也就是該註解被沒有被spring識別,問題的核心關鍵就在application類的註解SpringBootApplication上 

這個註解其實相當於下面這一堆註解的效果,其中一個註解就是@Component,在預設情況下只能掃描與控制器在同一個包下以及其子包下的@Component註解,以及能將指定註解的類自動註冊為Bean的@[email protected]和@ Repository,至此明白問題所在,之前我將介面與對應實現類放在了與控制器所在包的同一級目錄下,這樣的註解自然是無法被識別的 

所以有兩種解決辦法: 
  1 .將介面與對應的實現類放在與application啟動類的同一個目錄或者他的子目錄下,這樣註解可以被掃描到,這是最省事的辦法 
  2 .在指定的application類上加上這麼一行註解,手動指定application類要掃描哪些包下的註解。