Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a Spring 3 Bean into a JSF 2 Converter

I am trying to @javax.naming.Inject a Spring 3 Bean called WtvrBean into a JSF 2 @FacesConverter.

Both the Bean and the Converter are on the same package. And, in my spring's applicationContext.xml, I am scanning this package:

<context:component-scan base-package="my-package" />

But this is not working. For sure, the JSF 2 internal class that uses the converter is definitely not in my-package.

For instance, if I remove the @ManagedBean from a JSF 2 ManagedBean, and replace it to @org.springframework.stereotype.Component or @Controller, the WtvrBean can be @Injected on this ManagedBean, by using Spring WebFlow.

Well, as far as I know, there is no such thing as a @Converter stereotype in Spring.

I know I can use

FacesContextUtils.getWebApplicationContext(context).getBean("WtvrBean")

But, with that approach, the coupling between the web app and the spring is getting more tight. (annotations are metadata, and are not even considered dependency by some authors).

I am using FacesContextUtils so far, if there is no better solution.

Any ideas?

like image 710
bluefoot Avatar asked Feb 21 '11 18:02

bluefoot


2 Answers

If you want to inject beans into instances of a class, these instances have to be spring-managed. I.e. spring has to instantiate them. And this is not happening, so - no, you can't inject there.

But this is because you register the converter within jsf. You can skip that:

@Component("myConverter")
public class MyConverter implements Converter { .. }

And then, if you are using the spring <el-resolver>:

converter="#{myConverter}"

So that will do it. It has worked for me.

(A workaround worth mentioning is that you can do it by using aspectj weaving and @Configurable, but I'd prefer your FacesContextUtils approach. The weaving modifies classes so that they become spring managed even if they are not instantiated by spring.)

like image 113
Bozho Avatar answered Oct 07 '22 18:10

Bozho


@FacesConverter(value = "examTypeConverter")
@Named

Simple answer.

like image 32
Vamsi Kurukuri Avatar answered Oct 07 '22 19:10

Vamsi Kurukuri