[英]Inject dependencies into enum with guice(or Spring)
I'm integrating a servlet application with Guice (could be Spring, I choose Guice just because I worked with it). 我正在将一个servlet应用程序与Guice集成在一起(可能是Spring,我选择Guice只是因为我曾使用过它)。 And this application use constant-specific method extensively (thousands of enums).
并且此应用程序广泛使用特定于常量的方法(数千个枚举)。 From service, it determine the action to call:
通过服务,它确定要调用的操作:
ActionEnum act = ActionEnum.valueof("Action from context");
act.perform();
The enum action looks like this: 枚举动作如下所示:
public enum ActionEnum {
ACTION1 { perform() {}},
ACTION2 { perform() {}};
abstract void perform();
}
Is there any way to inject something in to the enum class by Guice (or Spring)? 有什么方法可以通过Guice(或Spring)向enum类中注入一些东西? eg:
例如:
public enum ActionEnum {
ACTION1 {
@Inject
SomeClass case1ToBeUsedByAction1;
void perform() {
case1ToBeUsedByAction1.doSomething();
case2ToBeUsedByActionN.doSomething();
}
},
ACTION2 { void perform() { case2ToBeUsedByActionN.doSomething(); }};
abstract void perform();
@Inject SomeClass case2ToBeUsedByActionN;
}
Or how do I change the current code base to enable injection? 或者如何更改当前代码库以启用注入?
You could add the class as an enum value like this: 您可以像这样将类添加为枚举值:
public enum TestType {
TEST_TYPE_1("TEST-1", Test1.class),
TEST_TYPE_2("TEST-2", Test2.class),
TEST_TYPE_3("TEST-3", Test3.class),
TEST_TYPE_4("TEST-4", Test4.class),
TEST_TYPE_5("TEST-5", Test5.class);
private final String testType;
private final Class<? extends TestIF> tester;
private <T extends TestIF> TestType(String testType, Class<? extends TestIF> tester) {
this.testType = testType;
this.tester = (Class<tester.TestIF>) tester;
}
public String toString() {
return this.testType;
}
public Class<? extends TestIF> tester() {
return this.tester;
}
and then implement the TestIF for each class and execute the injected classes like this: 然后为每个类实现TestIF并执行注入的类,如下所示:
TestIF tester = Guice.createInjector().getInstance(testType.tester());
tester.perform();
Instances of Java enum
are created at compile-time. Java
enum
实例在编译时创建。 Whereas instance creation and management by guice is dynamically executed during runtime. 而通过guice创建和管理实例是在运行时动态执行的。
Note that an enum
type cannot have a public constructor, which consolidates the fact that dynamic creation of an enum
type instance during runtime would not be possible. 请注意,
enum
类型不能具有公共构造函数,这巩固了以下事实:在运行时无法动态创建enum
类型实例。
Or how do I change the current code base to enable injection?
或者如何更改当前代码库以启用注入?
-- There's nothing you can do about the issue other than use a regular class
type. -除了使用常规的
class
类型之外,您无能为力。 Guice cannot do an injection into your enum class, since the injection is possible during runtime when enum
type instances would have been created already. Guice不能对您的enum类进行注入,因为在运行时可能已经创建了
enum
类型实例,所以注入是可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.