Skip to content

ServletContextInitializerBeans can't handle "scopedTarget." beans correctly. #7150

Closed

Description

@dantesun
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.IOException;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public DelegatingFilterProxyRegistrationBean myFilterRegistration() {
        return new DelegatingFilterProxyRegistrationBean("myFilter");
    }

    @Bean
    @RefreshScope
    public Filter myFilter() {
        return new GenericFilterBean() {
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                chain.doFilter(request, response);
            }
        };
    }
}

ServletContextInitializerBeans will register the "myFilter" bean twice. one is "myFilter"(by DelegatingFilterProxyRegistrationBean), the other is "scopedTarget.myFilter" due to the automatically find and add Filter type beans to ServletContext.

Spring boot version:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

Update: I remove the code not related to this issue.

Activity

  1. added
    status: waiting-for-triage
    on Oct 12, 2016
  2. philwebb commented on Oct 12, 2016

    @philwebb
    Member

    We had a similar issue with @MockBean (see #5724). I guess we need to filter the scopedTarget. versions.

  3. added
    type: bug
    and removed
    status: waiting-for-triage
    on Oct 12, 2016
  4. added this to the 1.4.2 milestone on Oct 12, 2016
  5. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    If there's no explicit FilterRegistrationBean declared, only one bean is registered as a filter and it's scopedTarget.myFilter. The problem appears to be that the logic in ServletContextInitializerBeans that looks for an existing registration bean doesn't find the one that's been created for the @RefreshScope Filter so it creates one and we end up with two.

  6. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    In the case where there's just myFilter (and no explicit registration bean), there are two bean definitions, one named myFilter and one named scopedTarget.myFilter. The latter matches when looking for beans of type Filter but the former does not. The former doesn't match as it's actually a ScopedProxyFactoryBean and there's insufficient type information available to match it as a Filter.

    When an explicit registration bean is added it has an interesting side-effect. It results in the myFilter bean being created earlier which gives the container more to go on when it's looking for a match. It no longer sees myFilter purely as a definition for a ScopedProxyFactoryBean but can now use the singleton instance for type matching. As a result, both myFilter and scopedTarget.myFilter are registered.

  7. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    There are two problems here:

    1. When there's no explicit FilterRegistrationBean the raw scopedTarget.myFilter bean is registered rather than myFilter which is the scoped proxy. This means that refresh has no effect.
    2. When there is an explicit FilterRegistrationBean the filter's registered twice. The faulty implicit registration described above and explicit registration. The explicit registration registers myFilter with the servlet container which is the scoped proxy so one of the two filters refreshes correctly.
  8. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    This change fixes both problems:

    diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java
    index ffafe68..a831c58 100644
    --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java
    +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java
    @@ -36,6 +36,7 @@ import javax.servlet.Servlet;
     import org.apache.commons.logging.Log;
     import org.apache.commons.logging.LogFactory;
    
    +import org.springframework.aop.scope.ScopedProxyUtils;
     import org.springframework.beans.factory.ListableBeanFactory;
     import org.springframework.beans.factory.support.BeanDefinitionRegistry;
     import org.springframework.core.annotation.AnnotationAwareOrderComparator;
    @@ -226,10 +227,10 @@ public class ServletContextInitializerBeans
                            }
    
                    };
    -               String[] names = beanFactory.getBeanNamesForType(type, true, false);
    +               String[] names = beanFactory.getBeanNamesForType(type, true, true);
                    Map<String, T> map = new LinkedHashMap<String, T>();
                    for (String name : names) {
    -                       if (!excludes.contains(name)) {
    +                       if (!excludes.contains(name) && !ScopedProxyUtils.isScopedTarget(name)) {
                                    T bean = beanFactory.getBean(name, type);
                                    if (!excludes.contains(bean)) {
                                            map.put(name, bean);

    However, it's relying on eager init being allowed to correctly determine the type that will be produced by the ScopedProxyFactoryBean. I doubt that that's a good idea.

  9. dantesun commented on Oct 14, 2016

    @dantesun
    Author

    @wilkinsona In RefreshScope, there's another flag controlling eager-init behavior. So "beanFactory.getBeanNamesForType(type, true, true)" won't eager init the "RefreshScope" bean with "eager" set to false. Am I right?

  10. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    The specifics of refresh scope are only one small part of it. Allowing eager init will initialise all lazy-init singletons and factory beans as part of the lookup and we don't want to do that.

  11. dantesun commented on Oct 14, 2016

    @dantesun
    Author

    A second thought, I don't quite understand why you want to eager init the beans. Maybe I am missing something...

  12. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    I think I explained that above:

    It's relying on eager init being allowed to correctly determine the type that will be produced by the ScopedProxyFactoryBean

  13. dantesun commented on Oct 14, 2016

    @dantesun
    Author

    Sorry, I miss that part.

  14. wilkinsona commented on Oct 14, 2016

    @wilkinsona
    Member

    Here's a small app that illustrates the problem:

    package com.example;
    
    import java.util.Arrays;
    
    import javax.annotation.PostConstruct;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Scope;
    import org.springframework.context.annotation.ScopedProxyMode;
    
    @SpringBootApplication
    public class Gh7150Application {
    
        @Autowired
        private ApplicationContext applicationContext;
    
        public static void main(String[] args) {
            String[] names = SpringApplication.run(Gh7150Application.class, args).getBeanNamesForType(MyBean.class, true, false);
            System.out.println("Names post refresh: " + Arrays.toString(names));
        }
    
        @PostConstruct
        public void postConstruct() {
            String[] names = this.applicationContext.getBeanNamesForType(MyBean.class, true, false);
            System.out.println("Names in post construct: " + Arrays.toString(names));
        }
    
        @Bean
        @Scope(scopeName="example", proxyMode=ScopedProxyMode.TARGET_CLASS)
        public MyBean myBean() {
            return new MyBean();
        }
    
        private static class MyBean {
    
        }
    
    }

    Its output is:

    Names in post construct: [scopedTarget.myBean]
    …
    Names post refresh: [scopedTarget.myBean, myBean]
    

    I think we may need an enhancement to the container so that myBean is found in post construct which is called before the ScopedProxyFactoryBean has been instantiated. @snicoll is on the case.

  15. changed the title [-]ServletContextInitializerBeans incorrectly handles @RefreshScope filters[/-] [+]ServletContextInitializerBeans can't handle "scopedTarget." beans correctly.[/+] on Oct 14, 2016
  16. wilkinsona commented on Oct 17, 2016

    @wilkinsona
    Member
  17. self-assigned this
    on Nov 1, 2016
  18. added a commit that references this issue on Nov 1, 2016
    4919c6f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions