是否可以通过向@Configuration注解传递名称来命名Spring配置类?

问题描述 投票:0回答:1

我正在构建一个 Kafka 流应用程序(Java/Spring),并有一个配置类,它像往常一样使用

@Value
为属性赋值。在配置类中,有一种方法可以根据这些值设置其他值,这对我来说是一种新的实践。没有
@Bean
注释。它看起来像这样:

@Configuration
public class SomeConfig {

    @Value("${some.value.we.use}")
    private String aConfigValue;

    @Value("${some.value.we.need}")
    private String anotherConfigValue;

    @PostConstruct
    public void configureIt() {
        if (aConfigValue != null) {
            System.setProperty("java.domain.this.thing", aConfigValue);
        }
        if (anotherConfigValue != null) {
            System.setProperty("java.domain.that.thing", anotherConfigValue);
        }
    }
}

在其他地方,此类在另一个类的

@DependsOn
注释中使用,如下所示:
@DependsOn("someConfig")

我相信

@DependsOn("someConfig")
很好,它会引用正确的类,但我想增加一些保证(通过提高我的知识或在代码中添加一些东西来增加我的信心)。

这会让我感觉更好,但我不知道这是否可能、是否是个好主意,或者是否有效。而且,我现在无法先尝试一下,所以我正在询问那些可能比我更了解的人。我知道我可以通过

@Bean
注释来命名 Bean,如下所示:
@Bean("someConfig")
,但我不会以这种方式声明 Bean。我也熟悉
@Qualifier
,但如果我可以按照我建议的方式命名该类,我不想使用它。

@Configuration("someConfig")
public class SomeConfig {

    @Value("${some.value.we.use}")
    private String aConfigValue;

    @Value("${some.value.we.need}")
    private String anotherConfigValue;

    @PostConstruct
    public void configureIt() {
        if (aConfigValue != null) {
            System.setProperty("java.domain.this.thing", aConfigValue);
        }
        if (anotherConfigValue != null) {
            System.setProperty("java.domain.that.thing", anotherConfigValue);
        }
    }
}

所以:

  1. 是否可以通过这种方式将名称传递给@Configuration注解来命名Spring配置类?如果是这样,你认为我应该吗?如果没有,为什么不呢?
  2. 在你看来,如果我以此为生,我是否错过了一些对我来说应该显而易见的东西? (我要去学习)

我还没有尝试过任何东西。还有其他代码没有附加注释或限定。这让我认为当类的名称为 SomeConfig 时,Spring 会将类读取为“someConfig”。实际名称足够常见,我不想在某个地方冒名称冲突的风险,并让 Spring 选择不属于此类的名称。

另外,由于这种模式对我来说是新的,而且我不习惯看到这种方式,所以我感到不安,并寻找一种让自己放心的方法。然而,由于我有很多存储库,其中这个或与此基本相同的东西正在生产中运行,所以我可以复制那里的内容而不再考虑它。但我不喜欢那样工作。

java spring-boot spring-annotations
1个回答
0
投票

由于这些类不是 Spring 配置类,您可以使用

@Component
来定义 bean:

@Component("someConfig")
public class SomeConfig {

    @Value("${some.value.we.use}")
    private String aConfigValue;

    @Value("${some.value.we.need}")
    private String anotherConfigValue;

    @PostConstruct
    public void configureIt() {
        if (aConfigValue != null) {
            System.setProperty("java.domain.this.thing", aConfigValue);
        }
        if (anotherConfigValue != null) {
            System.setProperty("java.domain.that.thing", anotherConfigValue);
        }
    }
}

此外,在这里设置 Java 系统属性然后依赖此 bean 可能不是一个好的模式。更好的方法是直接将配置值传递给依赖于

SomeConfig
的 bean。

© www.soinside.com 2019 - 2024. All rights reserved.