spring 條件化的bean

1、假設你希望一個bean只有在應用的類路徑下包含特定的庫時才創建。或者希望某個bean只有在另外的特定的bean也聲明瞭之後才創建。還可以設置某個特定的環境變量設置之後,纔會創建某個bean。

2、什麼地方會用到呢?

當創建bean是附件條件的時候。

3、舉個例子

package org.springframework.cloud.kubernetes.config.reload;

import io.fabric8.kubernetes.client.KubernetesClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.info.InfoEndpointAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.context.restart.RestartEndpoint;
import org.springframework.cloud.kubernetes.config.ConfigMapPropertySourceLocator;
import org.springframework.cloud.kubernetes.config.SecretsPropertySourceLocator;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Definition of beans needed for the automatic reload of configuration.
 *
 * @author Nicolla Ferraro
 */
@Configuration
@ConditionalOnProperty(value = "spring.cloud.kubernetes.enabled", matchIfMissing = true)
@ConditionalOnClass(EndpointAutoConfiguration.class)
@AutoConfigureAfter({ InfoEndpointAutoConfiguration.class,
		RefreshEndpointAutoConfiguration.class, RefreshAutoConfiguration.class })  //加載ConfigReloadAutoConfiguration之前先加載{}裏邊的類
@EnableConfigurationProperties(ConfigReloadProperties.class)    //使使用 @ConfigurationProperties 註解的類生效。
public class ConfigReloadAutoConfiguration {

	/**
	 * Configuration reload must be enabled explicitly.
	 */
	@ConditionalOnProperty("spring.cloud.kubernetes.reload.enabled")
	@ConditionalOnClass({ RestartEndpoint.class, ContextRefresher.class })
	@EnableScheduling
	@EnableAsync
	protected static class ConfigReloadAutoConfigurationBeans {

		@Autowired
		private AbstractEnvironment environment;

		@Autowired
		private KubernetesClient kubernetesClient;

		@Autowired
		private ConfigMapPropertySourceLocator configMapPropertySourceLocator;

		@Autowired
		private SecretsPropertySourceLocator secretsPropertySourceLocator;

		/**
		 * @param properties config reload properties
		 * @param strategy configuration update strategy
		 * @return a bean that listen to configuration changes and fire a reload.
		 */
		@Bean
		@ConditionalOnMissingBean
		public ConfigurationChangeDetector propertyChangeWatcher(
				ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy) {
			switch (properties.getMode()) {
			case POLLING:
				return new PollingConfigurationChangeDetector(this.environment,
						properties, this.kubernetesClient, strategy,
						this.configMapPropertySourceLocator,
						this.secretsPropertySourceLocator);
			case EVENT:
				return new EventBasedConfigurationChangeDetector(this.environment,
						properties, this.kubernetesClient, strategy,
						this.configMapPropertySourceLocator,
						this.secretsPropertySourceLocator);
			}
			throw new IllegalStateException(
					"Unsupported configuration reload mode: " + properties.getMode());
		}

		/**
		 * @param properties config reload properties
		 * @param ctx application context
		 * @param restarter restart endpoint
		 * @param refresher context refresher
		 * @return provides the action to execute when the configuration changes.
		 */
		@Bean
		@ConditionalOnMissingBean
		public ConfigurationUpdateStrategy configurationUpdateStrategy(
				ConfigReloadProperties properties, ConfigurableApplicationContext ctx,
				RestartEndpoint restarter, ContextRefresher refresher) {
			switch (properties.getStrategy()) {
			case RESTART_CONTEXT:
				return new ConfigurationUpdateStrategy(properties.getStrategy().name(),
						restarter::restart);
			case REFRESH:
				return new ConfigurationUpdateStrategy(properties.getStrategy().name(),
						refresher::refresh);
			case SHUTDOWN:
				return new ConfigurationUpdateStrategy(properties.getStrategy().name(),
						ctx::close);
			}
			throw new IllegalStateException("Unsupported configuration update strategy: "
					+ properties.getStrategy());
		}

	}

}

4、這裏涉及到了好幾個註解,我們逐個分析它們的作用。

  • @Configuration  //加入spring容器的bean是一個配置類
  • @ConditionalOnProperty(value = "spring.cloud.kubernetes.enabled", matchIfMissing = true) //配置文件中相應的屬性被設置成true是纔會創建這個bean
  • @ConditionalOnClass(EndpointAutoConfiguration.class)  //只不過判斷某個類是否存在於 classpath 中
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章