2016-04-18 4 views
8

Mi chiedo perché l'iniezione sul campo funzioni nella classe @SpringBootApplication e l'iniezione del costruttore no.Avvio a molla Nessuna funzione di costruzione predefinita trovata su @SpringBootApplication class

mio ApplicationTypeBean funziona come previsto, ma quando voglio avere un'iniezione costruttore CustomTypeService ricevo questa eccezione:

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

C'è qualche motivo per cui non funziona @SpringBootApplication classe?


La mia classe 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; 
} 

La mia classe @Service:

@Service 
public class CustomTypeService { 

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

La mia classe @Component:

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

    private String type; 

risposta

6

SpringBootApplication è una meta un notazione:

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

Così baiscally, il vostro ThirdPartyGlobalAndCustomTypesApplication è anche una molla Configuration di classe. Come Configuration s' javadoc stati:

@Configuration è meta-annotato con @Component, quindi @Configuration classi sono candidati per la scansione dei componenti (in genere utilizzando elemento di primavera XML) e quindi può inoltre usufruire di @ Autowired/@ Inject sul campo e livello metodo (ma non al livello costruttore).

quindi non è possibile utilizzare l'iniezione di costruzione per Configuration classi. Apparentemente sarà corretto nella release 4.3, basata su this answer e questo jira ticket.

+1

Grazie per il vostro chiarimento! – Patrick

+1

La citazione è la chiave. Avevo bisogno di effettuare il downgrade dalla 4.3. dove questo è fattibile. – sschrass

Problemi correlati