VaadinCDI @Inject not working in a class derived from CustomComponent

Hello,

I create Vaadin CDI test project. In my project i wrote the following code…
// TestComponent.java
@UIScoped
public class TestComponent extends CustomComponent {

@Inject
TestBean2 testBean2;

public TestComponent() {
VerticalLayout content = new VerticalLayout();
setCompositionRoot(content);

content.addComponent(new Label(“TestComponent”));
content.addComponent(new Label(testBean2.getMessage()));
}

}

// SecondView.java
@CDIView(“secondview”)
public class SecondView extends CustomComponent implements View {

@Inject
private TestBean testbean;
@Inject
TestComponent testComponent;
@Override
public void enter(ViewChangeEvent event) {
VerticalLayout content = new VerticalLayout();
setCompositionRoot(content);
content.addComponent(new Label(“SecondView”));
content.addComponent(new Label(testbean.getMessage()));
content.addComponent(testComponent);
}
}

In Cdi view injection of TestComponent works but in TestComponent injection not working and throws null pointer exception.

Please Help
Emir Cem

Hi,
if you use field injection you cannot use the bean in the constructor.
In TestComponent you should either use constructor injection or move the initialization login in a method annotated with @PostConstruct (that will be invoked after field injection)

HTH
Marco

Thank you very much Marco. It worked with constructor injection.

Its a bad idea to annotate component UIScoped until you plan to use it only in ui. (most of the time It must cleaned up as soon as you change the view, in your case bean and all its dependencies will be in container until you request a new ui, it also
can cause
different issues if you inject this component somewhere else like twice in same view in different nested components).

What is the reason to inject components, which problem you trying to solve? You got this component twice one time in the container and its also serialized in vaadin session.I would avoid doing such things. What you can do is having some bean which produce you an component kinda factory or builder

@NormalViewScoped
public void ComponentBuilder {

public Component build() {
//assemble you component
}

//set dependencies

}

public void MyView extends View {
@Inject
private ComponentBuilder builder;

public void enter(...) {
     setContent(builder.build());
}

}

This way vaadin will serialize a thiny proxy. and you got clean component.

You must do injections with very
caution
. Because its easly will blown up your session