Spring boot在@SpringBootApplication类上找不到默认构造函数

Pat*_*ick 10 java spring spring-boot

我想知道为什么字段注入在@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>()
Run Code Online (Sandbox Code Playgroud)

有什么理由不在@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;
}
Run Code Online (Sandbox Code Playgroud)

我的@Service类:

@Service
public class CustomTypeService {

    public void process(){
        System.out.println("CustomType");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的@Component类:

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

    private String type;
Run Code Online (Sandbox Code Playgroud)

Ali*_*ani 7

SpringBootApplication 是一个元注释:

// Other annotations
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication { ... }
Run Code Online (Sandbox Code Playgroud)

所以,你ThirdPartyGlobalAndCustomTypesApplication也是一个Spring Configuration课程.由于Configurationjavadoc的状态:

@Configuration使用@Component进行元注释,因此@Configuration类是组件扫描的候选者(通常使用Spring XML的元素),因此也可以在字段和方法级别利用@Autowired/@Inject(但不能在构造函数中使用)水平).

所以你不能对Configuration类使用构造函数注入.显然它将在4.3版本中修复,基于这个答案和这个jira票.