Refresh bean with spring cloud's @RefreshScope support

王宇轩 edited this page Feb 12, 2018 · 3 revisions

Refresh bean with spring boot's @RefreshScope support

Prerequisite

  • Spring 4.3.x
  • Spring Boot 1.4.x

Add spring cloud dependency

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-context</artifactId>
	<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-autoconfigure</artifactId>
	<version>1.4.1.RELEASE</version>
</dependency>

Mark the bean with @RefreshScope and @EnableAutoConfiguration

@Component("exampleBeanWithSpel")
@RefreshScope
@EnableAutoConfiguration // somewhere
public class ExampleBeanWithSpel {

	@Value("#{propertyGroup1['string_property_key']}")
	private String stringProperty;

	@Value("#{propertyGroup1['int_property_key']}")
	private int intProperty;

	private String computedValue;

	@PostConstruct
	private void init() {
		computedValue = stringProperty + intProperty;
	}

	public void someMethod() {
		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
	}

}

Register the bean observed

ExampleBeanWithSpel bean = context.getBean(ExampleBeanWithSpel.class);
GeneralConfigGroup cg1 = (GeneralConfigGroup) context.getBean("propertyGroup1");

cg1.register(new IObserver() {

	@Override
	public void notified(String data, String value) {
		context.getBean(RefreshScope.class).refresh("exampleBeanWithSpel");
	}
});

Example code

config-toolkit-demo

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.