Skip to content

@RefreshScope and component-scanned @ControllerAdvice beans. #1452

Description

@smar21

This is in 2.1.3.RELEASE, and Spring Boot 2.1.7.

Beans that are annotated with both @RefreshScope and @ControllerAdvice, and which are component-scanned (as opposed to explicit configuration) have their @ModelAttribute methods executed twice per incoming request, as opposed to once. One of the executions is via the proxy, the other is direct.

Simple example:

package test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestMain
{
    public static void main(final String[] args)
    {
        SpringApplication.run(TestMain.class, args);
    }
}

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;

@RefreshScope
@ControllerAdvice
public class TestAdvice
{
    private static final Logger logger = LoggerFactory.getLogger(TestAdvice.class);

    @Value("${test}")
    private String testConfigValue;
    
    @ModelAttribute
    public void adviceMethod(final HttpServletRequest httpServletRequest)
    {
        logger.info("advice method executed with " + testConfigValue);
    }
}

package test;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController
{
    @GetMapping(value = "/test")
    public String test()
    {
        return "test";
    }
}

Requests to the controller log as so:

2019-08-20 14:05:07.237 INFO 5156 --- [nio-8080-exec-5] test.TestAdvice : advice method executed with testvalue
2019-08-20 14:05:07.237 INFO 5156 --- [nio-8080-exec-5] test.TestAdvice : advice method executed with testvalue

Remove the @RefreshScope, and they log just once.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions