【问题标题】:Spring boot No default constructor found on @SpringBootApplication classSpring Boot 在@SpringBootApplication 类上找不到默认构造函数
【发布时间】:2016-08-10 08:35:03
【问题描述】:

我想知道为什么字段注入在@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 类:

@Service
public class CustomTypeService {

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

我的@Component 类:

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

    private String type;

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    SpringBootApplication 是一个元注释:

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

    所以说白了,你的 ThirdPartyGlobalAndCustomTypesApplication 也是一个 Spring Configuration 类。正如Configurationjavadoc 所说:

    @Configuration 使用@Component 进行元注释,因此 @Configuration 类是组件扫描的候选对象 (通常使用 Spring XML 的元素)和 因此也可以在现场利用@Autowired/@Inject 和方法级别(但不是构造函数级别)。

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

    【讨论】:

    • 感谢您的澄清!
    • 报价是关键。我需要从 4.3 降级。这是可行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2012-03-06
    • 2022-09-23
    • 2012-01-10
    • 2020-06-19
    • 2013-12-24
    • 1970-01-01
    相关资源
    最近更新 更多