2016-04-18 112 views
8

我想知道爲什麼字段注入在@SpringBootApplication類中工作,而構造函數注入不能。Spring引導在@SpringBootApplication類上找不到默認構造函數

ApplicationTypeBean爲預期的工作,但是當我想擁有的CustomTypeService構造注入我收到此異常:

Failed to instantiate [at.eurotours.ThirdPartyGlobalAndCustomTypesApplication$$EnhancerBySpringCGLIB$$2a56ce70]: No default constructor found; nested exception is java.lang.NoSuchMethodException: at.eurotours.ThirdPartyGlobalAndCustomTypesApplication$$EnhancerBySpringCGLIB$$2a56ce70.<init>() 

有什麼理由不爲@SpringBootApplication類工作?


我SpringBootApplication類:

@SpringBootApplication 
public class ThirdPartyGlobalAndCustomTypesApplication implements CommandLineRunner{ 

@Autowired 
ApplicationTypeBean applicationTypeBean; 

private final CustomTypeService customTypeService; 

@Autowired 
public ThirdPartyGlobalAndCustomTypesApplication(CustomTypeService customTypeService) { 
    this.customTypeService = customTypeService; 
} 

@Override 
public void run(String... args) throws Exception { 
    System.out.println(applicationTypeBean.getType()); 
    customTypeService.process(); 
} 

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

public CustomTypeService getCustomTypeService() { 
    return customTypeService; 
} 

我@服務類:

@Service 
public class CustomTypeService { 

    public void process(){ 
     System.out.println("CustomType"); 
    } 
} 

我@Component類:

@Component 
@ConfigurationProperties("application.type") 
public class ApplicationTypeBean { 

    private String type; 

回答

6

SpringBootApplication是一元一個記法:

// Other annotations 
@Configuration 
@EnableAutoConfiguration 
@ComponentScan 
public @interface SpringBootApplication { ... } 

所以baiscally,你ThirdPartyGlobalAndCustomTypesApplication也是春天Configuration類。作爲Configurationjavadoc狀態:

@Configuration是間使用了@Component註解,因此 @Configuration類是用於組分掃描 (通常使用Spring XML的元素)和 候選因此也可採取的優點@自動佈線/ @注入 和方法級別(,但不在構造函數級別)。

所以你不能使用Configuration類的構造函數注入。顯然它將在4.3版本中得到修復,基於this answer和這個jira ticket

+1

感謝您的澄清! – Patrick

+1

報價是關鍵。我需要從4.3降級。這是可行的。 – sschrass

相關問題