Search code examples
javaspringff4j

Spring injection not working for FF4J web console


I am try to get the FF4j (ff4j.org) web console to work. According to the documentation on the website, I use the following configuration:

<servlet>
    <servlet-name>ff4j-console</servlet-name>
    <servlet-class>org.ff4j.web.embedded.ConsoleServlet</servlet-class>
    <init-param>
        <param-name>ff4jProvider</param-name>
        <param-value><path to class>.ConsoleFF4jProvider</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>ff4j-console</servlet-name>
    <url-pattern>/ff4j-console</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

My implementation of FF4JProvider is:

import org.ff4j.FF4j;
import org.ff4j.web.api.FF4JProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * Created by itaykl on 17/06/2015.
 */
@Component
public class ConsoleFF4jProvider implements FF4JProvider{

    @Autowired
    private FF4j ff4j;

    public ConsoleFF4jProvider() {
    }

    @Override
    public FF4j getFF4j() {
        return ff4j;
    }
}

My problem is that no matter what I do I cannot get the autowiring of ff4j to work. Whenever the ConsoleServlet gets to the method call of getFF4J(), the ff4j class member is null.

I have tried using several other servlets together with the FF4J console and tried defining the ff4j bean in several ways.

Currently it is defined as:

<bean id="ff4j" class="org.ff4j.FF4j" ></bean>

But nothing seems to work.

If anyone found a solution to this problem and can share it, I would really appreciate it.


Solution

  • As I was saying in my comments, the constructor of FF4j wasn't invoked yet when you are trying to access to bean in ConsoleFF4jProvider. It is because Spring loads first ConsoleFF4jProvider and not beans defined in web.xml. To solve this problem you can remove:

    @Autowired
    private FF4j ff4j;
    

    and modify your getFF4j() function as following:

    @Override
    public FF4j getFF4j() {
        final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(FF4j.class); 
        context.refresh();
    
        FF4j ff4j= context.getBean(FF4j.class);
        return ff4j;
    }
    

    Or you can initialize ff4j in constructor as well.

    Edit: Otherwise you can add

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    

    to the constructor of ConsoleFF4jProvider

    Hope this will solve your issue.