bluefoot
bluefoot

Reputation: 10580

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?

Upvotes: 8

Views: 9124

Answers (4)

rbdharnia
rbdharnia

Reputation: 1

hey i was facing the same problem that spring beans are not getting injected in the JSF Converter.

then by googling about it i found the answers that after JSF 2.2 we can make converters as jsf managed bean. and then we can inject the spring dependency. it solved my problem.

 @ManagedBean
 @RequestScoped
 public class CustomerByName implements Converter {

      @ManagedProperty(value = "#{customerDao}")
      private CustomerDao customerDao;

and in your jsf page use it like a managed bean

 converter="#{customerByName}"

Upvotes: 0

Vamsi Kurukuri
Vamsi Kurukuri

Reputation: 29

@FacesConverter(value = "examTypeConverter")
@Named

Simple answer.

Upvotes: 2

Bozho
Bozho

Reputation: 597254

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.)

Upvotes: 16

Arek
Arek

Reputation: 3176

Add @Scope annotation (eg with "request" parameter) to your managed bean.

@ManagedBean
@Scope("request")
public class MyBean {
....
}

Upvotes: -1

Related Questions