我可以使用另一个 Annotation 作为 Spring @Qualifier 的值吗?

凯恩

奇怪的情况,但我正在从 dagger/dropwizard 框架迁移到 Spring。在旧框架中,代码使用了一堆自定义@interface Annotations 来指定哪个bean 去哪里。

例如,可能有这样的注释

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ForAdmin {}

提供者有这样的代码

@Provides
@ForAdmin
static Foobar provideFoobar() { ... }

并像这样注入

public MyObject(@ForAdmin Foobar foobar) { ... }

在 Spring 世界中,我知道我可以将提供者翻译成

@Bean("ForAdmin")
public Foobar provideFoobar() { }

并像这样注入

public MyObject(@Qualifier("ForAdmin") Foobar foobar) { ... }

我想知道是否有办法将现有@ForAdmin注释本身作为限定符提供。

有点像...

@Bean(ForAdmin.class)
public Foobar provideFoobar() { }

这可能吗?有更好的方法吗?

我想这样做的原因是保留原始注释,以便将它们放在那里的开发人员仍然熟悉它们,并且可以通过他们已经知道的关于使用 IDE 的注释来跟踪 bean 和注入。

尼古拉·舍甫琴科

您可以使用与以前完全相同的方法

假设一个接口有 2 个实现:

interface Foobar {}

class FoobarAll implements Foobar {}

class FoobarAdmin implements Foobar {}

以及产生@Beans的配置

@Configuration
class FoobarConfig {
    @Bean
    Foobar provideFoobarAll() { return new FoobarAll(); }

    @ForAdmin
    @Bean
    Foobar provideFoobarAdmin() { return new FoobarAdmin(); }
}

并注入了一个类 Foobar

@Component
class FoobarConsumer {
    private final Foobar foobar;

    public FoobarConsumer(@ForAdmin Foobar foobar) {
        this.foobar = foobar;
        System.out.println("I am " + this.foobar.getClass().getSimpleName()); 
        // >>> I am FoobarAdmin
    }
}

PS 为了简化你的代码,你甚至不需要 a@Configuration来产生@Beans,你可以简单地在你的类上放置@Component@ServiceSpring 注释。然后 Spring 会自动实例化这些 bean。

@Component
class FoobarAll implements Foobar {}

@ForAdmin
@Component
class FoobarAdmin implements Foobar {}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以使用一个熊猫表作为另一个的映射表吗?

在Spring中可以使用多个@Qualifier注释吗?

我可以在 C 中的另一个 if 语句中使用 if 语句作为条件吗?

我可以使用返回值作为参数多次运行同一个函数吗?

Spring Boot-在@Qualifier上使用可配置的值

我可以使用成员函数作为EnumWindows的第一个参数吗

我可以使用嵌入层而不是一个热点作为类别输入吗?

有没有更好的方法可以使用另一个字典中的值作为键来查询字典中的值?

使用张量的值作为另一个的形状?

我可以使用Spring作为CDI来混合JEE和Spring注释吗?

我可以将图像作为 blob 存储到 localstorage 或其他地方以便它可以在另一个页面中使用吗?

我们可以将两个函数作为另一个函数的参数传递吗?

我可以做一个使用RSI值作为条件的while循环吗?

我可以创建一个编译错误来检查一个特性是否具有另一个特性作为超特性吗?

我可以指定因子水平作为另一个数据集的排序变量吗?

我可以将类作为扩展添加到 Kotlin 中的另一个类吗?

我可以使变量的值取决于对另一个变量的更改吗?

我可以使用另一个#define指令重新定义宏吗?

我可以使用变量模板来声明另一个变量模板吗?

我可以使用PropertyResourceConfigurer的setOrder方法覆盖另一个PropertyResourceConfigurer的属性吗?

我可以使用`fetch`运行另一个JS脚本吗?

我可以使用另一个结构中的结构成员吗?

我可以使用dd将系统移动到另一个分区吗?

我可以使用Java从另一个窗口读取文本吗?

我可以使用另一个类内部的函数中的变量吗?

我可以使用“包含页面”控件从另一个Db加载XPage吗?

如果我们使用会话身份验证,用户可以作为另一个用户闯入 django 服务器并执行操作吗?

我可以通过使用另一个ssh服务器作为中介来访问ssh服务器吗

我可以在已经拥有 Redux 的项目中使用上下文 API 作为几乎另一个事实来源吗?