001/** 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.spring.boot; 017 018import org.springframework.context.annotation.Condition; 019import org.springframework.context.annotation.ConditionContext; 020import org.springframework.context.annotation.Conditional; 021import org.springframework.core.env.*; 022import org.springframework.core.type.AnnotatedTypeMetadata; 023 024import java.lang.annotation.ElementType; 025import java.lang.annotation.Retention; 026import java.lang.annotation.RetentionPolicy; 027import java.lang.annotation.Target; 028import java.util.Iterator; 029 030 031@Target({ElementType.TYPE, ElementType.METHOD}) 032@Retention(RetentionPolicy.RUNTIME) 033@Conditional(ConditionalOnMybatisFlexDatasource.OnMybatisFlexDataSourceCondition.class) 034public @interface ConditionalOnMybatisFlexDatasource { 035 036 class OnMybatisFlexDataSourceCondition implements Condition { 037 038 @Override 039 public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { 040 Environment env = context.getEnvironment(); 041 if (env instanceof AbstractEnvironment) { 042 MutablePropertySources propertySources = ((AbstractEnvironment) env).getPropertySources(); 043 Iterator<PropertySource<?>> it = propertySources.stream().iterator(); 044 while (it.hasNext()) { 045 PropertySource ps = it.next(); 046 if (ps instanceof MapPropertySource) { 047 for (String propertyName : ((MapPropertySource) ps).getSource().keySet()) { 048 if (propertyName.startsWith("mybatis-flex.datasource.")) { 049 return true; 050 } 051 } 052 } 053 } 054 } 055 return false; 056 } 057 } 058 059}