【问题标题】:Can I qualify an injection based on an Enum?我可以根据枚举来限定注入吗?
【发布时间】:2015-01-15 17:14:43
【问题描述】:

我们有一些遗留代码,我正试图找出一种清理方法。我想到的一个解决方案是,也许我可以根据给定的枚举值注入一个自定义处理程序。我可以根据枚举来限定注入吗?我可能在想这样的事情(伪代码)

@Service(MyEnum.MYVALUE, MyEnum.MYOTHERVALUE) // produces a handler given these enums
public class MyHandler { ... }

@Service(MyEnum.ANOTHERVALUE)
public class AnotherHandler {... }

// .... some mystical way of telling spring what my current enum context is so I can get the right handler

【问题讨论】:

标签: java spring enums spring-3


【解决方案1】:

我认为这行不通。

首先,@ServicevalueString,而不是Enum[]。而且,它只是建议为该服务类注册的 bean 的名称。

相反,我认为您可能想要使用的是@Qualifier。所以,你可以有类似的东西:

@Service
@Qualifier("foo")
public class FooHandler implements IHandler { ... }

@Service
@Qualifier("bar")
public class BarHandler implements IHandler { ... }

@Component
public class MyThing {
    @Autowired @Qualifier("foo")
    private IHandler handler;

    ...
}

或者,您可以创建自己的自定义限定符注释,例如:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@Qualifier
public @interface MyQualifier { ... }

@Service
@MyQualifier
public class FooHandler implements IHandler { ... }

@Component
public class MyClass {
    @Autowired @MyQualifier
    private IHandler handler;

    ...
}

更多详情请见Fine-tuning annotation-based autowiring with qualifiers

【讨论】:

  • 并不是真的暗示@Service 参数是一个枚举,这就是我说“伪代码”的原因,我不确定我要查找的代码是什么
【解决方案2】:

好吧,您可以尝试创建自己的验证(是的,即使使用枚举),然后提供您自己的 BeanPostProcessor 来完成这项工作并将值注入您的注释字段。

有很多 Spring BeanPostProcessor,所以你可以通过浏览 Spring 的源代码来了解它是如何完成的。

【讨论】:

    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多