Spring @Component和@Configuration用于基本配置类,有什么区别?

4

我有一些需要配置的服务,因此这些服务都与一个配置类相关联。

例如:

class ExampleService {
    @Autowired
    ExampleConfiguration conf;

    ...
}

class ExampleConfiguration {
    private String exampleProperty;

    public void setExampleProperty(String exampleProperty) {
        this.exampleProperty = exampleProperty;
    }

    public String getExampleProperty() {
        return exampleProperty;
    }
}

那么ExampleConfiguration必须声明为@Component或@Configuration(或另一个注释:)吗?而此类不定义任何bean,它只是一个基本配置。
1个回答

4
我认为你误解了 @Configuration 注释的用法。它应该用于基于注释的配置,而不是基于 xml 的配置。并且必须与 @Bean 注释一起使用,以定义在运行时可用的 bean。
看起来你实际上想要定义一个将存储某些配置属性的 bean。要自动装配它,你只需使用 @Component 标记它。你还需要告诉 Spring 上下文它可以通过 component-scan 找到这个 bean。

好的,谢谢。我之前不太确定,现在因为你讲得很清楚了 :) - Kakawait

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接