0

My Spring-based web application uses JSF as a presentation layer. To make working Spring @Autowired annotation in my backing beans and to have a clean project structure I do not use any JSF-managed bean, converter nor a validator. All my beans has a @Component and @Scope annotation with a particular attributes.

Problem:

One of my converters uses database and its EntityManager should be injected via @Autowired. I figured out, that the converter is properly created by Spring, but JSF manages it either! JSF creates its own instances of my converter and uses them instead of using the instances created by Spring.

Note:

I reference the converter though EL evaluation: <f:converter binding="#{myConverter}"/>

Environment:

My environment is Oracle JDK 6, 64b Linux OS, com.sun JSF 2.1 implementation, Spring 3.1.3.

Questions:

  1. Why JSF creates its own instances of my converter when I reference it via #{myConverter}
  2. How did JSF figure out the class of converter because I didn't used @FacesConverter neither defined it in faces-config.xml?
  3. Is there any way to force JSF to use only Spring-managed instances?

Code to reproduce:

MyConverter.java

@Scope( "singleton" )
@Component( "myConverter" )
public class MyConverter implements Converter {

    private MyBean bean;

    public MyConverter() {
        System.out.println( "MyConverter created with no arg constructor" );
    }

    @Autowired
    public MyConverter( MyBean bean ) {
        System.out.println( "MyConverter created with parametrized constructor" );
        this.bean = bean;
    }

    @Override
    public Object getAsObject( FacesContext context, UIComponent component, String value ) {
        System.out.println( "Bean value is " + bean );
        return value;
    }

    @Override
    public String getAsString( FacesContext context, UIComponent component, Object value ) {
        System.out.println( "Bean value is " + bean );
        return value.toString();
    }
}

JSF index.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">

<h:body>

    <h:form>

        <h:inputText value="#{myBean.text}">
            <f:converter binding="#{myConverter}"/>
        </h:inputText>

        <h:commandButton value="Create" action="#{myBean.action}"/>

    </h:form>

</h:body>

</html>
4

0 回答 0