Finding a bean instance #10562
-
Suppose I have a bean factory that creates @Singleton
public class MyBeanFactory {
@Bean
@RequestScope
public RequestScopedBean create(XmlMapper xmlMapper, Locale locale) {
return new RequestScopedBean(xmlMapper, locale);
}
} Assuming I want to use @Controller
HomeController {
@Inject RequestScopedBean bean;
//..more code
@Get("/myResource")
public String getResource(Locale locale) {
//at this point I expect that a new instance of RequestScopedBean to be available in this particular
//bean context (scope request)
//moreover, I want this instance has to be injected with an XmlMapper (singleton) and the "locale" Locale (request scoped)
//bean that was discovered by the RequestLocaleResolver and put on this bean context
bean.doStuff();
}
} It does not work simply because controllers have singleton scope and one cannot inject beans with narrower scope there. So I have a few questions:
Regarding point 1 import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.spi.CDI;
@RequestScoped
public class RequestScopedBean {
// impl here
}
public class MyClass {
public void doSomethingWithRequestScopedBean() {
// obtain the current instance of RequestScopedBean within the request scope
RequestScopedBean requestScopedBean = CDI.current().select(RequestScopedBean.class).get();
requestScopedBean.doStuff();
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
That's not how it works; instead of |
Beta Was this translation helpful? Give feedback.
as per the error message if you want to do that introduce an interface that you inject. Proxying types with constructors needs a public no args constructor by default.