我想知道为什么字段注入(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
类。如Configuration
的javadoc所述:因此,您不能对
Configuration
类使用构造函数注入(inject)。显然,它将基于this answer和此jira ticket在4.3版本中进行修复。