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() {
setCompositionRoot(menuBar);
}
}
@UIScoped
public class MyMenuBar extends CustomComponent {
private Label label;
private MenuBar menuBar;
@Inject
public MyMenuBar(@New Label label, @New MenuBar menuBar) {
setCompositionRoot(menuBar);
}
}
Is there any best practice? Why choose one option over another? Or is it just a matter of personal choice?
source
share