I'm using CDI in Vaadin context, but that should not matter for my question: Is it in general better to inject objects inside the constructor, or directly as a member variable? Especially if these objects have to be further configured for the component to work.
The following shows two different CDI possibilities:
@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 a best practice? Why should one prefer the one option over the other? Or is it just a matter of personal choice?