Initialize CDI injection components in a constructor or post method?

I use CDI in the context of Vaadin, but that doesn't matter for my question: Is it generally better to inject objects inside the constructor or directly as a member variable? Especially if these objects must be additionally configured for the component to work.

Two features of CDI are shown below:

@UIScoped
public class MyMenuBar extends CustomComponent {
    @Inject @New private Label label;
    @Inject @New private MenuBar menuBar;

    @PostConstruct
    private void init() {
        //set label text, define menu entries
        setCompositionRoot(menuBar);
    }
}

@UIScoped
public class MyMenuBar extends CustomComponent {
    private Label label;
    private MenuBar menuBar;

    @Inject
    public MyMenuBar(@New Label label, @New MenuBar menuBar) {
        //set label text, define menu entries
        setCompositionRoot(menuBar);
    }
}

Is there any best practice? Why choose one option over another? Or is it just a matter of personal choice?

+4
source share
2 answers

@PostConstruct (, CDI EJB beans), , bean ( ). , , ( , ).

- , , init, . , @PostConstruct .

+4

; .. - . Allways @PostConstruct . . .

, "" .

, @PostConstruct ( ).

+6

All Articles