CDI at a Component

I am using Vaadin 8 with CDI, JavaEE7 and wildfly12

I have a Class which extends a ComboBox. I use this class later in a CDIView.

@CDI-Annotation
public class LanguageSelector extends ComboBox<Locale> {

	@Inject
	SettingsService settings;

	public LanguageSelector() {
		setItems(getLanguageList());
		setValue(settings.getDefaultLanguage());
		setEmptySelectionAllowed(false);
		addValueChangeListener(e -> {
			getUI().setLocale((Locale) getValue());
		});
	}

	private List<Locale> getLanguageList() {
		List<Locale> languageList = new ArrayList<>();
		languageList.add(Locale.ENGLISH);
		languageList.add(Locale.GERMAN);
		return languageList;
	}
}

In this Class i want to inject the Bean SettingsService, which holds the data of a database.

My Question:

Is this possible?

Which Annotation can i take here?

Is this possible?

Yes. Is it good practice? It depends on specific use case.

Which Annotation can i take here?

It really depends what you want to achieve. If you use annotation @UIScoped it will mean that same instance of LanguageSelector is shared in all views in your UI, i.e. if you inject it to more than one. If you use annotation @ViewScoped new instance of LanguageSelector is created by bean manager per each view you use it with.

See more here (e.g. the chat box example)

https://vaadin.com/docs/v8/framework/advanced/advanced-cdi.html

Thanks for your reply, great.

But now i get the error:

no active context for scope com.vaadin.cdi.ViewScoped

My Code-example is.

First the Class with the Annotation @ViewScoped

@ViewScoped
public class LanguageSelector extends ComboBox<Locale> {

	@Inject
	SettingsService settings;

	public LanguageSelector() {
		setItems(getLanguageList());
		setValue(settings.getDefaultLanguage());
		setEmptySelectionAllowed(false);
		addValueChangeListener(e -> {
			getUI().setLocale((Locale) getValue());
		});
	}

	private List<Locale> getLanguageList() {
		List<Locale> languageList = new ArrayList<>();
		languageList.add(Locale.ENGLISH);
		languageList.add(Locale.GERMAN);
		return languageList;
	}
}

And then the class where i inject the @ViewScoped - LanguageSelector

@UIScoped
public class LoginView extends VerticalLayout implements View {

	@Inject
	private LanguageSelector languageSelector;

	public LoginView() {
	....
	}

	@PostConstruct
	void init() {
		languageSelector.setCaption("Language");
		addComponent(languageSelector);
	}
}

Sounds like your case you are trying to inject to a view not registered by the add-on. Your LoginView should be annotated @CDIView(“viewname”) and you should setup the Navigator according to our documentation with CDIViewProvider, etc.

Thanks for your answer.
now it works.