2016-04-18 75 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

相关问题