spring-cloud-commons icon indicating copy to clipboard operation
spring-cloud-commons copied to clipboard

@RefreshScope breaks bean order

Open OPorta opened this issue 5 years ago • 4 comments

Describe the bug When autowiring a list of beans, Order annotation can be used to order this list of beans. If we add the RefreshScope annotation in one of these beans then this bean gets order=Ordered.LOWEST_PRECEDENCE and the list is not ordered anymore.

Sample

Custom Object:

public class CustomObject {
	private String name;
	public CustomObject(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

Spring configuration:

@Configuration
public class BeanConfiguration {
	
	@Bean
	//@RefreshScope
	@Order(1)
	public CustomObject firstBean() {
		return new CustomObject("first");
	}
	
	@Bean
	@Order(2)
	public CustomObject secondBean() {
		return new CustomObject("second");
	}
}

Test:

@SpringBootTest
class DemoApplicationTests {

	@Autowired
	List<CustomObject> names;
	
	@Test
	void testOrder() {
		Assertions.assertThat(names.stream().map(CustomObject::getName)).containsExactly("first", "second");
	}

}

When @RefreshScope is added at "firstBean" our test fails.

OPorta avatar Apr 30 '20 13:04 OPorta

@dsyer is there something we can do about this?

spencergibb avatar Feb 17 '21 16:02 spencergibb

I'm not sure I believe that @Order is applied to those beans even without @RefreshScope. I tend to think you got lucky. Happy to be proved wrong.

dsyer avatar Feb 17 '21 16:02 dsyer

After docs research

You can declare the @Order annotation at the target class level and on @Bean methods, potentially for individual bean definitions (in case of multiple definitions that use the same bean class). @Order values may influence priorities at injection points, but be aware that they do not influence singleton startup order, which is an orthogonal concern determined by dependency relationships and @DependsOn declarations.

But we'll need some framework help on how to deal with it.

spencergibb avatar Mar 08 '22 15:03 spencergibb

Maybe @rstoyanchev could point us in the right direction.

spencergibb avatar Mar 08 '22 15:03 spencergibb