Search code examples
springspring-mvcproxy-classes

Check the state validity of a Spring proxied bean without try-catch


I have a bean being created by a service with the following class:

@Configuration
public class AccessManager {

    @Bean(name="access", destroyMethod="destroy")
    @Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
    @Autowired
    public Access create(HttpServletRequest request) {
        System.out.println(request.getRemoteAddr());
        return new Access();
    }

}

Everything works as expected, except that when the application is starting, this method is being called, probably because I have some other singleton beans that use the Access bean. At the start up there is no request bound to the Thread, and it's expected to get a java.lang.IllegalStateException when trying to access any property of the request parameter.

No problem. The question is, is it possible to check if the underlying HttpServletRequest of the proxy request is null before calling a property that raises the exception?


Solution

  • You probably want to take a look at RequestContextHolder#getRequestAttributes(). That will return null if you're not currently in a context where request scope could be used.

    @Configuration
    public class AccessManager {
    
        @Bean(name="access", destroyMethod="destroy")
        @Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
        @Autowired
        public Access create(HttpServletRequest request) {
            if (RequestContextHolder.getRequestAttributes() != null) {
                System.out.println(request.getRemoteAddr());
            }
            return new Access();
        }
    
    }