gpt4 book ai didi

java - Spring Boot 在@SpringBootApplication 类上找不到默认构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:20:23 25 4
gpt4 key购买 nike

我想知道为什么字段注入(inject)在 @SpringBootApplication 类中起作用,而构造函数注入(inject)却不起作用。

我的 ApplicationTypeBean 正在按预期工作,但是当我想对 CustomTypeService 进行构造函数注入(inject)时,我收到此异常:

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类:

@Service
public class CustomTypeService {

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

我的@Component 类:

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

private String type;

最佳答案

SpringBootApplication 是一个元注解:

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

因此,您的 ThirdPartyGlobalAndCustomTypesApplication 也是一个 Spring Configuration 类。作为配置javadoc状态:

@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning (typically using Spring XML's element) and therefore may also take advantage of @Autowired/@Inject at the field and method level (but not at the constructor level).

因此您不能对Configuration 类使用构造函数注入(inject)。显然它将在 4.3 版本中修复,基于 this answer还有这个jira ticket .

关于java - Spring Boot 在@SpringBootApplication 类上找不到默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com