@Inject = @Inject,可以吗? [英] @Inject = @Inject, is it possible?

查看:93
本文介绍了@Inject = @Inject,可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java EE 8,并且我有下一个枚举.问题是是否可以像下一行一样将一个类别内另一个注入变量的值分配给一个注入变量?

I'm using Java EE 8 and I have next enum. The question is is it possible assign to the one injected variable the value of another injected variable within one class like on the next line?

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支持 @PostConstruct 注释:

Yes, it is possible - but only after CDI had a chance to inject a value. CDI supports @PostConstruct annotation for this purpose:

使用 @PostConstruct 注释初始化托管Bean初始化托管bean会指定在依赖项注入之后但在类投入使用之前CDI框架应调用的生命周期回调方法.

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. 在托管bean类或其任何超类中,定义一个执行所需初始化的方法.
  2. 使用 javax.annotation.PostConstruct 注释对方法的声明进行注释.
  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.

将托管bean注入组件时,在所有注入都已发生并且所有初始化程序都已被调用之后,CDI会调用该方法.

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.

注意:根据JSR 250的要求,如果在超类中声明了带注释的方法,则除非声明类的子类覆盖该方法,否则将调用该方法.

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.

添加以下方法将对您有所帮助:

Adding the method below will have an effect you are looking for:

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

这篇关于@Inject = @Inject,可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆