@Inject = @Inject,这可能吗?

@Inject = @Inject, is it possible?

我正在使用 Java EE 8,我有下一个枚举。问题是 是否可以像下一行那样,将另一个注入变量的值分配给一个 class 中的另一个注入变量?

public enum CommandEnum {

    EMPTY_COMMAND {
        {
            this.command = emptyCommand;
        }
    },
    NAME_GENERATION {
        {
            this.command = nameGenerationCommand;
        }
    },
    NAME_GENERATION_SETTINGS {
        {
            this.command = nameGenerationSettingsCommand;
        }
    },
    SIGNIN {
        {
            this.command = signinCommand; // is it possible?
        }
    };

    @Inject
    @EmptyCommandQualifier
    Command command;
    @Inject
    EmptyCommand emptyCommand;
    @Inject
    NameGenerationCommand nameGenerationCommand;
    @Inject
    NameGenerationSettingsCommand nameGenerationSettingsCommand;
    @Inject
    SigninCommand signinCommand;

    public Command getCommand() {
        return command;
    }
}

谢谢。

是的,这是可能的 - 但前提是 CDI 有机会注入一个值。 CDI supports @PostConstruct annotation for this purpose:

To Initialize a Managed Bean Using the @PostConstruct Annotation Initializing a managed bean specifies the lifecycle callback method that the CDI framework should call after dependency injection but before the class is put into service.

  1. In the managed bean class or any of its superclasses, define a method that performs the initialization that you require.
  2. Annotate the declaration of the method with the javax.annotation.PostConstruct annotation.

When the managed bean is injected into a component, CDI calls the method after all injection has occurred and after all initializers have been called.

Note: As mandated in JSR 250, if the annotated method is declared in a superclass, the method is called unless a subclass of the declaring class overrides the method.

添加下面的方法会有你想要的效果:

@PostConstruct
public void init () {
    this.command = signinCommand;
}