3

I'm programming a Tomcat application which serves as a proxy for some internal services.

I've switched my Spring project from a mixed XML and annotation-based configuration to Java and annotation based configuration.

Before switching the configuration style, the app worked fine. Now I have two issues.

  1. when executing init-methods in two of my filters, ApplicationContext is null. When I debug my App, I can see that the Method setApplicationContext is executed.

  2. the EntityManagerFactory is not injected in the authentication filter (emf is null)

Code for booting Spring:

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class MyAppSpringBoot implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        initRootContext(container);
        initDispatcherContext(container);
        addFilters(container);
    }

    private void initDispatcherContext(ServletContext container) {
        AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext();
        servletContext.register(MyAppDispatcherServletContext.class);
        ServletRegistration.Dynamic dispatcher
                = container.addServlet("myAppDispatcherServlet", new DispatcherServlet(servletContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }

    private void initRootContext(ServletContext container) {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(MyAppRootContext.class);
        container.addListener(new ContextLoaderListener(rootContext));
    }

    private void addFilters(ServletContext container) {
        FilterRegistration.Dynamic registration
                = container.addFilter("u3rAuthentication", UserDbAuthenticationFilter.class);
        registration.addMappingForUrlPatterns(null, false, "/entry/*");

        registration = container.addFilter("responseXmlFilter", ResponseTextXmlFilter.class);
        registration.addMappingForUrlPatterns(null, false, "/entry/*");
    }
}

Code for root context:

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Controller;

@Configuration
@ComponentScan(basePackages = "com.application", excludeFilters = @ComponentScan.Filter(Controller.class))
public class MyAppRootContext {

    @Bean
    public DataSource userDbJpaDataSource() throws DataSourceLookupFailureException {

        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
        return lookup.getDataSource("jdbc/userDbPostgres");
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        //return Persistence.createEntityManagerFactory(MyAppConstants.U3R_PERSISTENCE_UNIT);
        LocalContainerEntityManagerFactoryBean fb = new LocalContainerEntityManagerFactoryBean();
        fb.setDataSource(userDbJpaDataSource());
        return fb.getNativeEntityManagerFactory();
    }

    @Bean
    public DiskFileItemFactory diskFileItemFactory() {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(50_000 * 1024);
        factory.setRepository(new File("/WEB-INF/upload"));
        return factory;
    }

    @Bean
    public XMLOutputFactory xmlOutputFactory() {
        return XMLOutputFactory.newInstance();
    }

    @Bean
    public XMLInputFactory xmlInputFactory() {
        return XMLInputFactory.newInstance();
    }

    @Bean
    public XMLEventFactory xmlEventFactory() {
        return XMLEventFactory.newInstance();
    }

    @Bean
    public UrlPairing urlPairing() throws IOException {
        return new UrlPairing(myAppProperties().getProperty("myApp.UrlPairingFile"));
    }

    @Bean
    public Properties myAppProperties() throws IOException {
        Properties p = new Properties();
        p.load(MyAppRootContext.class.getResourceAsStream("/myAppConfig.properties"));
        return p;
    }

    @Bean
    public MyAppXmlFilterWords xmlFilterWords() throws IOException {
        MyAppXmlFilterWords words = MyAppXmlFilterWords.createFilterWords(myAppProperties().getProperty("myApp.xmlFilterWordFile"));
        return words;
    }

}

Code for dispatcher servlet context:

@Configuration
@ComponentScan(
        basePackages = "de.lgn.doorman",
        includeFilters = @ComponentScan.Filter(Controller.class)
)
public class MyAppDispatcherServletContext
{
    // all beans are defined in root context
    // correct ???
}

Code for root authentication filter:

@Component
public class UserDbAuthenticationFilter implements Filter, ApplicationContextAware
{
    private static final Logger logger = LogManager.getLogger(UserDbAuthenticationFilter.class.getName());

    @Autowired
    EntityManagerFactory emf;

    private ApplicationContext appContext;

    @Override
    public void init(FilterConfig filterConfig)    
    {
        logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
        // *******************  NullPointerException here *******************
    }

    @Override
    public void destroy()
    { }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        appContext = applicationContext;
    }

    /*
    @PostConstruct    // ***************** this annotation isn't working **********************
    public void filterInit() throws ServletException
    {
        logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
    }

    */
}

In my controller, the ApplicationContext is correct (not null).

@Controller
@RequestMapping(value = "entry/**")
public class MyAppProxyController implements ApplicationContextAware
{

    @Autowired
    Properties myAppProperties;

    private ApplicationContext appContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        appContext = applicationContext;
    }

    @PostConstruct
    public void init() throws ServletException   // this is working fine
    {
        logger.debug("Controller {} initialisiert. App-Context: {} {}", this.getClass().getName(),
                appContext.hashCode(), appContext);

        logger.debug("Beans im Zugriff von Controller:");
        for (String beanName : appContext.getBeanDefinitionNames())
        {
            logger.debug("          {}", beanName);
        }
        MyAppProxyController controller = (MyAppProxyController) appContext.getBean("myAppProxyController");
        logger.debug("controller-hash im Controller={}", controller.hashCode());
    }
}    

Update to the answer of Serge Ballesta

I followed all your instructions #2. But now I get this exception:

13-Aug-2015 13:03:27.264 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [de.lgn.doorman.config.DmSpringBoot@c427b4f]
13-Aug-2015 13:03:27.655 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
13-Aug-2015 13:03:28.308 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.filterStart Exception starting filter responseXmlFilter
 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'responseXmlFilter' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1174)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)

I wonder how my own filters are connected to the chain when I use three times DelegatingFilterProxy. Is the paramter name in the method addFilter associated with the bean name?

Update 2 to the answer of Serge Ballesta

This is the code for creating the filter chain in the bootstrap code:

private void addFilters(ServletContext container)
{
    FilterRegistration.Dynamic registration =
            container.addFilter("userDbAuthenticationFilter", DelegatingFilterProxy.class);
    registration.addMappingForUrlPatterns(null, false, "/mapgate/*");

    registration = container.addFilter("prepareRequestFilter", DelegatingFilterProxy.class);
    registration.addMappingForUrlPatterns(null, false, "/mapgate/*");

    registration = container.addFilter("responseTextXmlFilter", DelegatingFilterProxy.class);
    registration.addMappingForUrlPatterns(null, false, "/mapgate/*");
}

These are my filter bean definitions in the root context:

@Configuration
@ComponentScan(basePackages = "com.application", excludeFilters = @ComponentScan.Filter(Controller.class))
public class MyAppRootContext
{

    @Bean
    public UserDbAuthenticationFilter userDbAuthenticationFilter()
    {
        return new UserDbAuthenticationFilter();
    }

    @Bean
    public PrepareRequestFilter prepareRequestFilter()
    {
        return new PrepareRequestFilter();
    }

    @Bean
    public ResponseTextXmlFilter responseTextXmlFilter()
    {
        return new ResponseTextXmlFilter();
    }

    @Bean
    public DataSource userDbJpaDataSource() throws DataSourceLookupFailureException
    {

        JndiDataSourceLookup lookup = new JndiDataSourceLookup();
        return lookup.getDataSource("jdbc/userDbPostgres");
    }

    @Bean
    public EntityManagerFactory entityManagerFactory()
    {
        LocalContainerEntityManagerFactoryBean fb = new LocalContainerEntityManagerFactoryBean();
        fb.setDataSource(userDbJpaDataSource());
        return fb.getNativeEntityManagerFactory();
    }
}

There is still no dependency injection to the filters. Is it because the filter chain is created during the bootstrap phase, and the beans are created in the root context?

Update 3 to the answer of Serge Ballesta

This is the essential code in the authentication filter :

public class U3RAuthenticationFilter implements Filter, ApplicationContextAware
{
    private static final Logger logger = LogManager.getLogger(U3RAuthenticationFilter.class.getName());

    @Autowired(required = true)
    EntityManagerFactory entityManagerFactory;

    private ApplicationContext appContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        appContext = applicationContext;
    }

    @PostConstruct
    public void filterInit() throws ServletException
    {
        logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
        logger.debug("Beans accessable by {}:", this.getClass().getName());
        for (String beanName : appContext.getBeanDefinitionNames())
        {
            logger.debug("          {}", beanName);
        }

        logger.debug("EntityManagerFactory: {}", (EntityManagerFactory)appContext.getBean("entityManagerFactory"));
    }
}

No exception is thrown. This the logging:

20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1] controller-hash im Controller=1481031354
20150814-090718 INFO  [RMI TCP Connection(3)-127.0.0.1] Mapped "{[/mapgate/**],methods=[GET]}" onto protected void com.application.controller.MyAppProxyController.doGet(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
20150814-090718 INFO  [RMI TCP Connection(3)-127.0.0.1] Mapped "{[/mapgate/**],methods=[POST]}" onto protected void com.application.controller.MyAppProxyController.doPost(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws javax.servlet.ServletException,java.io.IOException
20150814-090718 INFO  [RMI TCP Connection(3)-127.0.0.1] Looking for @ControllerAdvice: WebApplicationContext for namespace 'myAppDispatcherServlet-servlet': startup date [Fri Aug 14 09:07:18 CEST 2015]; parent: Root WebApplicationContext
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1] Filter com.application.filter.UserDbAuthenticationFilter initialisiert. App-Context: 641348200 WebApplicationContext for namespace 'myAppDispatcherServlet-servlet': startup date [Fri Aug 14 09:07:18 CEST 2015]; parent: Root WebApplicationContext
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1] Beans accessable by com.application.filter.UserDbAuthenticationFilter:
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.internalConfigurationAnnotationProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.internalAutowiredAnnotationProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.internalRequiredAnnotationProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.internalCommonAnnotationProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.internalPersistenceAnnotationProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.event.internalEventListenerProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.event.internalEventListenerFactory
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           myAppDispatcherServletContext
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           myAppRootContext
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           myAppProxyController
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           requestMappingHandlerMapping
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcContentNegotiationManager
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           viewControllerHandlerMapping
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           beanNameHandlerMapping
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           resourceHandlerMapping
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcResourceUrlProvider
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           defaultServletHandlerMapping
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           requestMappingHandlerAdapter
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcConversionService
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcValidator
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcPathMatcher
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcUrlPathHelper
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcUriComponentsContributor
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           httpRequestHandlerAdapter
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           simpleControllerHandlerAdapter
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           handlerExceptionResolver
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           mvcViewResolver
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           userDbAuthenticationFilter
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           prepareRequestFilter
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           responseTextXmlFilter
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           myAppFilterChain
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           userDbJpaDataSource
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           <b>entityManagerFactory</b>
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           diskFileItemFactory
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           xmlOutputFactory
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           xmlInputFactory
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           xmlEventFactory
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           urlPairing
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           myAppProperties
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1]           xmlFilterWords
20150814-090718 DEBUG [RMI TCP Connection(3)-127.0.0.1] <b>EntityManagerFactory: null</b>
2
  • Is it a typo, you have rootContext.register(DmRootContext.class); in your WebApplicationInitializer, and your root context configuration class is public class MyAppRootContext? Commented Aug 13, 2015 at 9:44
  • @SergeBallesta - yes it is a typo, but not in my real code. Thanks. Commented Aug 13, 2015 at 9:46

2 Answers 2

3

The culprit is addFilter(..) method of MyAppSpringBoot.

If you look closely at this LOC FilterRegistration.Dynamic registration = container.addFilter("u3rAuthentication", UserDbAuthenticationFilter.class); it will be evident that even though the UserDbAuthenticationFilter is registered with ServletContext as filter, it is not associated with spring context in any way (since the class is directly registered and not the spring bean which will explain the null references of ApplicationContext and emf respectively).

Although same class UserDbAuthenticationFilter is scanned by spring and registered as bean later but is not associated with ServletContext as filter (this bean is never invoked as it is not registered as filter and this is where you see your ApplicationContext being set while debugging)

So there are two instances for same class UserDbAuthenticationFilter one as filter with servlet and another as spring bean with no association / link with each other.

What you need here is a filter registered with servlet container which is a spring bean as well. GenericFilterBean comes to your rescue. Extend it as per your need and be aware of the below gotcha (from API docs)

This generic filter base class has no dependency on the Spring ApplicationContext concept. Filters usually don't load their own context but rather access service beans from the Spring root application context, accessible via the filter's ServletContext (see WebApplicationContextUtils).

Hope this helps. Let know in comments in case you face any issues / need further help.

Sign up to request clarification or add additional context in comments.

Comments

1

As the application context is correctly injected in your controller, I assume that Spring is correctly initialized. But your filters are declared as raw filters, not as spring beans, so the spring annotations are ignored on them.

You have two ways to get access to the application context:

  1. a raw filter (not Spring enabled) can get access to the root application context with WebApplicationContext WebApplicationContextUtils.getWebApplicationContext(ServletContext sc). For example, you could change your init method:

    @Override
    public void init(FilterConfig filterConfig)    
    {
        ServletContex sc = filterConfig.getServletContext();
        appContext = WebApplicationContextUtils.getWebApplicationContext(sc);
        logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
    }
    
  2. you can also use a DelegatingFilterProxy to effectively use beans as filters:

    Change add filter to:

    private void addFilters(ServletContext container) {
        FilterRegistration.Dynamic registration
                = container.addFilter("u3rAuthentication", DelegatingFilterProxy.class);
        registration.addMappingForUrlPatterns(null, false, "/entry/*");
    
        registration = container.addFilter("responseXmlFilter", DelegatingFilterProxy.class);
        registration.addMappingForUrlPatterns(null, false, "/entry/*");
    }
    

    add filter beans in your root context:

    @Bean
    public UserDbAuthenticationFilter u3rAuthentication() { 
        return new UserDbAuthenticationFilter();
    }
    
    @Bean
    public ResponseTextXmlFilter responseXmlFilter() { 
        return new ResponseTextXmlFilter();
    }
    

    the init method will no longer be called, but this would work:

    @PostConstruct
    public void filterInit() throws ServletException
    {
        logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
    }
    

7 Comments

You're right, there were differences in the names used in bean definition and addFilter calls. I corrected this, and now it seems the filter chain is created. But the EntityManagerFactory is not injected to UserDbAuthenticationFilter. I'll update my question.
It should work. I cannot reproduce the problem. Double check the debug log for beans creation and initialization, try @Autowired(required=true) EntityManagerFactory emf; to force an error it bean is created without finding the entity manager factory and share the stack trace.
I've inserted @Autowired(required=true) and modified the method annotated with @PostContruct. Please, see my updated question.
I accept your answer because it was a lot of help. I've discovered that I made a mistake in the method which creates the EntityManagerFactory bean , so this method returns NULL. But I wonder why there is no exception cause by @Autowired(required=true) . Perhaps I'll create another question.
@Ulrich: I've read your log again. The filter is created in servlet context when it should be created in root context : UserDbAuthenticationFilter initialisiert...WebApplicationContext for namespace 'myAppDispatcherServlet-servlet...parent: Root WebApplicationContext: you have problems between root and application context. You should control which beans are created in which context.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.