下面列出了怎么用org.springframework.context.annotation.Conditional的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Provide IDP Metadata
*
* @return
* @throws MetadataProviderException
*/
@Bean
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public ExtendedMetadataDelegate idpMetadata() throws MetadataProviderException {
Timer backgroundTaskTimer = new Timer(true);
HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(backgroundTaskTimer, new HttpClient(),
singleSignOnConfig.getMetadataUrl());
httpMetadataProvider.setParserPool(parserPool());
ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider,
extendedMetadata());
extendedMetadataDelegate.setMetadataTrustCheck(true);
extendedMetadataDelegate.setMetadataRequireSignature(true);
return extendedMetadataDelegate;
}
@Bean
@DependsOn("logFeederSecurityConfig")
@Conditional(NonCloudStorageCondition.class)
public LogSearchConfigLogFeeder logSearchConfigLogFeeder() throws Exception {
if (logFeederProps.isUseLocalConfigs()) {
LogSearchConfigLogFeeder logfeederConfig = LogSearchConfigFactory.createLogSearchConfigLogFeeder(
Maps.fromProperties(logFeederProps.getProperties()),
logFeederProps.getClusterName(),
LogSearchConfigLogFeederLocal.class, false);
logfeederConfig.setLogLevelFilterManager(logLevelFilterManager());
return logfeederConfig;
} else {
return LogSearchConfigFactory.createLogSearchConfigLogFeeder(
Maps.fromProperties(logFeederProps.getProperties()),
logFeederProps.getClusterName(),
LogSearchConfigLogFeederZK.class, false);
}
}
@Bean
@Conditional(NonCloudStorageCondition.class)
public LogLevelFilterManager logLevelFilterManager() throws Exception {
if (logFeederProps.isSolrFilterStorage()) {
SolrClient solrClient = new LogFeederSolrClientFactory().createSolrClient(
logFeederProps.getSolrZkConnectString(), logFeederProps.getSolrUrls(), logFeederProps.getSolrMetadataCollection(),
logFeederProps.isSolrCloudDiscover());
return new LogLevelFilterManagerSolr(solrClient);
} else if (logFeederProps.isUseLocalConfigs() && logFeederProps.isZkFilterStorage()) {
final HashMap<String, String> map = new HashMap<>();
for (final String name : logFeederProps.getProperties().stringPropertyNames()) {
map.put(name, logFeederProps.getProperties().getProperty(name));
}
return new LogLevelFilterManagerZK(map);
} else {
return null;
}
}
@Bean
@Conditional({ SchedulerConfiguration.SchedulerConfigurationPropertyChecker.class })
public SchedulerService schedulerService(CommonApplicationProperties commonApplicationProperties,
List<TaskPlatform> taskPlatforms, TaskDefinitionRepository taskDefinitionRepository,
AppRegistryService registry, ResourceLoader resourceLoader,
ApplicationConfigurationMetadataResolver metaDataResolver,
SchedulerServiceProperties schedulerServiceProperties,
AuditRecordService auditRecordService,
TaskConfigurationProperties taskConfigurationProperties,
DataSourceProperties dataSourceProperties) {
return new DefaultSchedulerService(commonApplicationProperties,
taskPlatforms, taskDefinitionRepository,
registry, resourceLoader,
taskConfigurationProperties, dataSourceProperties, null,
metaDataResolver, schedulerServiceProperties, auditRecordService);
}
@Bean
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public SAMLProcessorImpl processor() {
Collection<SAMLBinding> bindings = new ArrayList<>();
ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(httpClient());
HTTPSOAP11Binding soapBinding = new HTTPSOAP11Binding(parserPool());
artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding));
bindings.add(httpRedirectDeflateBinding());
bindings.add(httpPostBinding());
bindings.add(new HTTPArtifactBinding(parserPool(), velocityEngine(), artifactResolutionProfile));
bindings.add(new HTTPSOAP11Binding(parserPool()));
bindings.add(new HTTPPAOS11Binding(parserPool()));
return new SAMLProcessorImpl(bindings);
}
@Bean
@Conditional(AspectJOnClasspathCondition.class)
public TimeLimiterAspect timeLimiterAspect(
TimeLimiterConfigurationProperties timeLimiterConfigurationProperties,
TimeLimiterRegistry timeLimiterRegistry,
@Autowired(required = false) List<TimeLimiterAspectExt> timeLimiterAspectExtList,
FallbackDecorators fallbackDecorators,
SpelResolver spelResolver
) {
return new TimeLimiterAspect(timeLimiterRegistry, timeLimiterConfigurationProperties, timeLimiterAspectExtList, fallbackDecorators, spelResolver);
}
/**
* Creates a GrpcServerFactory using the shaded netty. This is the recommended default for gRPC.
*
* @param properties The properties used to configure the server.
* @param serviceDiscoverer The discoverer used to identify the services that should be served.
* @param serverConfigurers The server configurers that contain additional configuration for the server.
* @return The shadedNettyGrpcServerFactory bean.
*/
@ConditionalOnClass(name = {"io.grpc.netty.shaded.io.netty.channel.Channel",
"io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder"})
@Conditional(ConditionalOnInterprocessServer.class)
@Bean
public ShadedNettyGrpcServerFactory shadedNettyGrpcServerFactory(final GrpcServerProperties properties,
final GrpcServiceDiscoverer serviceDiscoverer, final List<GrpcServerConfigurer> serverConfigurers) {
final ShadedNettyGrpcServerFactory factory = new ShadedNettyGrpcServerFactory(properties, serverConfigurers);
for (final GrpcServiceDefinition service : serviceDiscoverer.findGrpcServices()) {
factory.addService(service);
}
return factory;
}
/**
* @param retryConfigurationProperties retry configuration spring properties
* @param retryRegistry retry in memory registry
* @return the spring retry AOP aspect
*/
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public RetryAspect retryAspect(
RetryConfigurationProperties retryConfigurationProperties,
RetryRegistry retryRegistry,
@Autowired(required = false) List<RetryAspectExt> retryAspectExtList,
FallbackDecorators fallbackDecorators,
SpelResolver spelResolver
) {
return new RetryAspect(retryConfigurationProperties, retryRegistry, retryAspectExtList,
fallbackDecorators, spelResolver);
}
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public CircuitBreakerAspect circuitBreakerAspect(
CircuitBreakerRegistry circuitBreakerRegistry,
@Autowired(required = false) List<CircuitBreakerAspectExt> circuitBreakerAspectExtList,
FallbackDecorators fallbackDecorators,
SpelResolver spelResolver
) {
return new CircuitBreakerAspect(circuitBreakerProperties, circuitBreakerRegistry,
circuitBreakerAspectExtList, fallbackDecorators, spelResolver);
}
/**
* Springdoc bean factory post processor 2 bean factory post processor.
*
* @return the bean factory post processor
*/
// For spring-boot-1 compatibility
@Bean
@Conditional(CacheOrGroupedOpenApiCondition.class)
@ConditionalOnMissingClass(value = BINDRESULT_CLASS)
@Lazy(false)
static BeanFactoryPostProcessor springdocBeanFactoryPostProcessor2() {
return SpringdocBeanFactoryConfigurer::initBeanFactoryPostProcessor;
}
/**
* Default Kerberos ticket validator
*
* @return
*/
@Bean
@Conditional(InsightsKerberosBeanInitializationCondition.class)
public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
Resource storeFile = resourceLoaderService
.getResource("file:" + singleSignOnConfig.getKeyTabLocationKerberos());
SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
ticketValidator.setServicePrincipal(singleSignOnConfig.getServicePrincipalKerberos());
ticketValidator.setKeyTabLocation(storeFile);
ticketValidator.setDebug(true);
return ticketValidator;
}
/**
* used to provide Metadata Manager
*
* @return
* @throws MetadataProviderException
*/
@Bean
@Qualifier("metadata")
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public CachingMetadataManager metadata() throws MetadataProviderException {
List<MetadataProvider> providers = new ArrayList<>();
providers.add(idpMetadata());
return new CachingMetadataManager(providers);
}
@Bean
@Conditional(IgniteConditionalCache.class)
public IgniteCache<?, ?> messageIdCache() throws Exception {
@SuppressWarnings("rawtypes")
CacheConfiguration<?, ?> cacheConfiguration = new CacheConfiguration().setDataRegionName("not-persistence-data-region")
.setCacheMode(CacheMode.LOCAL).setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL).setName("messageIdCache");
return ignite().getOrCreateCache(cacheConfiguration);
}
@Bean
@Conditional(IgniteConditionalCache.class)
public IgniteCache<?, ?> messageCache() throws Exception {
@SuppressWarnings("rawtypes")
CacheConfiguration<?, ?> cacheConfiguration = new CacheConfiguration().setDataRegionName("persistence-data-region")
.setCacheMode(CacheMode.LOCAL).setName("retainMessageCache");
return ignite().getOrCreateCache(cacheConfiguration);
}
/**
* The {@link com.bugsnag.servlet.BugsnagServletContainerInitializer} does not work for Spring Boot, need to
* register the {@link BugsnagServletRequestListener} using a Spring Boot
* {@link ServletListenerRegistrationBean} instead. This adds session tracking and
* automatic servlet request metadata collection.
*/
@Bean
@Conditional(SpringWebMvcLoadedCondition.class)
ServletListenerRegistrationBean<ServletRequestListener> listenerRegistrationBean() {
ServletListenerRegistrationBean<ServletRequestListener> srb =
new ServletListenerRegistrationBean<ServletRequestListener>();
srb.setListener(new BugsnagServletRequestListener());
return srb;
}
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public RateLimiterAspect rateLimiterAspect(
RateLimiterConfigurationProperties rateLimiterProperties,
RateLimiterRegistry rateLimiterRegistry,
@Autowired(required = false) List<RateLimiterAspectExt> rateLimiterAspectExtList,
FallbackDecorators fallbackDecorators,
SpelResolver spelResolver
) {
return new RateLimiterAspect(rateLimiterRegistry, rateLimiterProperties,
rateLimiterAspectExtList, fallbackDecorators, spelResolver);
}
/** Setup {@link AWSSecurityTokenService} client an IAM role to assume is given. */
@Bean
@ConditionalOnMissingBean
@Conditional(STSSetCondition.class)
AWSSecurityTokenService securityTokenService(ZipkinSQSCollectorProperties properties) {
return AWSSecurityTokenServiceClientBuilder.standard()
.withCredentials(getDefaultCredentialsProvider(properties))
.withRegion(properties.awsStsRegion)
.build();
}
/**
* 当用户的环境配置了redisTemplate时则使用Redis做缓存
*
* @param realm realm
* @param redisTemplate spring RedisTemplate
* @return DefaultWebSecurityManager
*/
@Bean
@Conditional(RedisEnableCondition.class)
public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm, RedisTemplate<Object, Object> redisTemplate) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
//使用自定义的Redis缓存实现,依赖redisTemplate,keyNamespace可以默认为空
securityManager.setCacheManager(this.getCacheManager(redisTemplate));
return securityManager;
}
/**
* 当用户的环境没有配置redisTemplate时则使用ehcache做缓存
*
* @param realm realm
* @return DefaultWebSecurityManager
*/
@Bean
@Conditional(RedisDisabledCondition.class)
public DefaultWebSecurityManager webSecurityManager(Realm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
//使用ehcache当缓存
EhCacheManager cacheManager = new EhCacheManager();
securityManager.setCacheManager(cacheManager);
return securityManager;
}
/***
* 密码凭证匹配器,采用redis记录重试次数,超过指定次数则不允许登录
* @return
*/
@Bean
@Conditional(RedisEnableCondition.class)
public CredentialsMatcher retryLimitHashedCredentialsMatcher(RedisTemplate<Object, Object> redisTemplate) {
return credentialsMatcher(redisTemplate);
}
@SuppressWarnings( "unchecked" )
@Bean
@Qualifier( "notifier" )
@Conditional( RedisEnabledCondition.class )
public Notifier redisNotifier( ObjectMapper objectMapper )
{
return new RedisNotifier( (RedisTemplate<String, String>) redisTemplate, objectMapper );
}
@Bean
@Conditional(NonCloudStorageCondition.class)
@DependsOn({"inputConfigHandler"})
public InputConfigUploader inputConfigUploader() throws Exception {
return new InputConfigUploader("Input Config Loader", logSearchConfigLogFeeder(),
inputConfigManager(), logLevelFilterHandler());
}
@Conditional(MicroServiceCondition.class)
@Bean(name = "defaultConfigBean")
public Object defaultConfigBean() {
logger.info("create new DefaultConfigBean...");
return new Object();
}
@ConditionalOnResource(resources = "classpath:mysql.properties")
@Conditional(HibernateCondition.class)
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false");
return hibernateProperties;
}
@Bean(name = "cloudLogSearchLogFeederConfig")
@Conditional(CloudStorageCondition.class)
public LogSearchConfigLogFeeder cloudLogSearchLogFeederConfig() throws Exception {
return LogSearchConfigFactory.createLogSearchConfigLogFeeder(
Maps.fromProperties(logFeederProps.getProperties()),
logFeederProps.getClusterName(),
LogSearchConfigLogFeederLocal.class, false);
}
@SuppressWarnings("unchecked")
private List<String[]> getConditionClasses(AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(Conditional.class.getName(), true);
Object values = (attributes != null ? attributes.get("value") : null);
return (List<String[]>) (values != null ? values : Collections.emptyList());
}
public static boolean matches(ConditionContext context) {
Class<AuthorizationServerEndpointsConfigurationBeanCondition> type = AuthorizationServerEndpointsConfigurationBeanCondition.class;
Conditional conditional = AnnotationUtils.findAnnotation(type, Conditional.class);
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(type);
for (Class<? extends Condition> conditionType : conditional.value()) {
Condition condition = BeanUtils.instantiateClass(conditionType);
if (condition.matches(context, metadata)) {
return true;
}
}
return false;
}
/**
* Used to add filter chain based on Request Matcher
*
* @return
* @throws Exception
*/
@Bean
@Conditional(InsightsKerberosBeanInitializationCondition.class)
public FilterChainProxy kerberosFilter() throws Exception {
LOG.debug("message Inside InsightsSecurityConfigurationAdapterKerberos FilterChainProxy, initial bean **** ");
/*AuthenticationUtils.setSecurityFilterchain(
new DefaultSecurityFilterChain(new AntPathRequestMatcher("/kerberos/login/**"), spnegoEntryPoint()));*/
/*AuthenticationUtils.setSecurityFilterchain(new DefaultSecurityFilterChain(
new AntPathRequestMatcher("/user/insightsso/**"), insightsSSOProcessingFilter()));*/
List<Filter> filters = new ArrayList<>();
filters.add(0, new InsightsCustomCsrfFilter());
filters.add(1, new InsightsCrossScriptingFilter());
filters.add(2, insightsServiceProcessingFilter());
filters.add(3, new InsightsResponseHeaderWriterFilter());
AuthenticationUtils
.setSecurityFilterchain(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/**"), filters));
ListIterator<SecurityFilterChain> securityFilters = AuthenticationUtils.getSecurityFilterchains()
.listIterator();
while (securityFilters.hasNext()) {
SecurityFilterChain as = securityFilters.next();
LOG.debug("message Inside FilterChainProxy, initial bean name {} **** ",
Arrays.toString(as.getFilters().toArray()));
}
return new FilterChainProxy(AuthenticationUtils.getSecurityFilterchains());//chains
}
@Conditional(MicroServiceCondition.class)
@Bean(name = "conditionConfigBean")
public Object conditionConfigBean() {
logger.info("create new ConditionConfigBean...");
return new Object();
}
/**
* SAML 2.0 WebSSO Assertion Consumer
*
* @return
*/
@Bean
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public WebSSOProfileConsumer webSSOprofileConsumer() {
WebSSOProfileConsumerImpl webSSOProfileConsumerImpl = new WebSSOProfileConsumerImpl();
webSSOProfileConsumerImpl.setResponseSkew(600);
webSSOProfileConsumerImpl.setMaxAuthenticationAge(36000);
return webSSOProfileConsumerImpl;
}