Spring @Component vs @Configuration 用于基本配置类

标签 spring annotations

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

例如:

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 ,这只是一个基本的配置。

最佳答案

我想你误解了@Configuration的用法注解。它应该用于基于注解的配置,而不是基于 xml 的配置。并且必须与@Bean一起使用注释,用于定义运行时可用的 bean。

看起来您实际上想要定义将存储一些配置属性的 bean。要 Autowiring 它,你可以用 @Component 标记它.您还必须通过 component-scan 告诉 spring 上下文它可以在哪里发现这个 bean。 .

关于Spring @Component vs @Configuration 用于基本配置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18976634/

相关文章:

java - 使用 java MethodHandles 实现鸭子类型(duck typing)

java - Hibernate 在 Map 中映射 UserType

java - hive 中的线程 “main” java.lang.IllegalArgumentException中的异常

Spring AOP : Getting parameters of the pointcut annotation

针对不同消费者的每条消息的 Spring Cloud Stream 主题

spring - 如何在Aop中打印Grails Controller 参数对象值

java - Spring /DI : Constructor injection in child class

spring-boot - 如何配置@PreAuthorize 以识别我登录用户的 ID?

android - Kotlin 注释 : Get interface inner annotated properties

grails - Grails/GORM-相当于JPA @ElementCollection