没有配置的Spring构造函数注入(注释、XML、java配置)

没有配置的Spring构造函数注入(注释、XML、java配置),java,spring,dependency-injection,constructor-injection,Java,Spring,Dependency Injection,Constructor Injection,我对组件扫描bean的构造函数注入有问题。我有以下服务 public class SomeService implements ISomeService { private ISomeService2 someService2; public SomeService(ISomeService2 someService2) { this.someService2 = someService2; } . . . } 然后我有一个执行组件扫描的配置:

我对组件扫描bean的构造函数注入有问题。我有以下服务

public class SomeService implements ISomeService {
    private ISomeService2 someService2;
    public SomeService(ISomeService2 someService2) {
        this.someService2 = someService2;
    }
. . .
}
然后我有一个执行组件扫描的配置:

    @Configuration
    @ComponentScan(
            basePackages = "base.backage",
            includeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*"))
    public class AppConfig { }
然后我尝试解决以下问题:

    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    ISomeService someService1 = ctx.getBean(ISomeService.class);
这会引发异常java.lang.NoSuchMethodException(它没有默认的非参数构造函数)。我已经扫描并注册了IsomeService2bean。我可以简单地通过向某个服务构造函数添加@Autowired注释来修复它


有没有一种方法可以在默认情况下进行构造函数注入,而不使用类内部的注释、XML或特定bean上的任何显式配置?

Nope。您必须以某种方式告诉spring为该注释使用自动关联,或者自己指定关系。您可以在xml中指定按类型使用默认自动连接,但这将为所有内容启用它。ISomeService2是否符合Spring组件的条件?是-ISomeService2是Spring组件bean@M.Deinum如何按类型设置此默认自动布线?我每次都要使用构造函数注入。您必须包含一个xml文件,其中包含
default autowire=“constructor”
。然而,我强烈建议不要使用它。我建议您只需将
@Autowired
添加到您想要用于自动布线的构造函数中,这会使它不那么神奇。不。您必须以某种方式告诉spring为该注释使用自动关联,或者自己指定关系。您可以在xml中指定按类型使用默认自动连接,但这将为所有内容启用它。ISomeService2是否符合Spring组件的条件?是-ISomeService2是Spring组件bean@M.Deinum如何按类型设置此默认自动布线?我每次都要使用构造函数注入。您必须包含一个xml文件,其中包含
default autowire=“constructor”
。然而,我强烈建议不要使用它。我建议您只需将
@Autowired
添加到要用于自动布线的构造函数中,这会让它不那么神奇。