下面列出了怎么用org.springframework.core.type.AnnotatedTypeMetadata的API类实例代码及写法,或者点击链接到github查看源代码。
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
if (metadata.isAnnotated(Lazy.class.getName())) {
abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value"));
}
else if (abd.getMetadata() != metadata && abd.getMetadata().isAnnotated(Lazy.class.getName())) {
abd.setLazyInit(attributesFor(abd.getMetadata(), Lazy.class).getBoolean("value"));
}
if (metadata.isAnnotated(Primary.class.getName())) {
abd.setPrimary(true);
}
if (metadata.isAnnotated(DependsOn.class.getName())) {
abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value"));
}
if (abd instanceof AbstractBeanDefinition) {
AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
if (metadata.isAnnotated(Role.class.getName())) {
absBd.setRole(attributesFor(metadata, Role.class).getNumber("value").intValue());
}
if (metadata.isAnnotated(Description.class.getName())) {
absBd.setDescription(attributesFor(metadata, Description.class).getString("value"));
}
}
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
Configuration configuration = ApplicationProperties.get();
boolean shouldRunSetup = configuration.getBoolean(ATLAS_SERVER_RUN_SETUP_KEY, false);
if (shouldRunSetup) {
LOG.warn("Running setup per configuration {}.", ATLAS_SERVER_RUN_SETUP_KEY);
return true;
} else {
LOG.info("Not running setup per configuration {}.", ATLAS_SERVER_RUN_SETUP_KEY);
}
} catch (AtlasException e) {
LOG.error("Unable to read config to determine if setup is needed. Not running setup.");
}
return false;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("FlexyPoolConfigurationAvailable");
String propertiesFilePath = System.getProperty(PropertyLoader.PROPERTIES_FILE_PATH);
if (propertiesFilePath != null && ClassLoaderUtils.getResource(propertiesFilePath) != null) {
return ConditionOutcome.match(message.found("FlexyPool configuration file").items(propertiesFilePath));
}
if (ClassLoaderUtils.getResource(PropertyLoader.PROPERTIES_FILE_NAME) != null) {
return ConditionOutcome.match(message.found("FlexyPool configuration file").items(PropertyLoader.PROPERTIES_FILE_NAME));
}
return ConditionOutcome.noMatch(message.didNotFind("FlexyPool configuration file").atAll());
}
@Test
public void assertMatch() {
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty("spring.shardingsphere.rules.shadow.column", "user_id");
ConditionContext context = Mockito.mock(ConditionContext.class);
AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class);
when(context.getEnvironment()).thenReturn(mockEnvironment);
ShadowSpringBootCondition condition = new ShadowSpringBootCondition();
ConditionOutcome matchOutcome = condition.getMatchOutcome(context, metadata);
assertThat(matchOutcome.isMatch(), is(true));
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String ssoClass = "org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso";
boolean ssoClientAnnotationExists = ClassUtils.isPresent(ssoClass, null);
if(!ssoClientAnnotationExists){
return ConditionOutcome.match("EnableOAuth2Sso not exists!");
}
String[] beanNames = context.getBeanFactory().getBeanNamesForAnnotation(EnableOAuth2Sso.class);
if(beanNames==null || beanNames.length==0){
return ConditionOutcome.match("not @EnableOAuth2Sso bean found!");
}
return ConditionOutcome.noMatch("@EnableOAuth2Sso sso client!");
}
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
try {
return conditionContext.getEnvironment().getProperty("realMongo", Boolean.class);
}
catch (Exception e){
return false;
}
}
@Override
public boolean matches( ConditionContext context, AnnotatedTypeMetadata metadata )
{
if ( !isTestRun( context ) )
{
return getConfiguration().getProperty( ConfigurationKey.REDIS_ENABLED ).equalsIgnoreCase( "true" );
}
return false;
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String dbEngine = System.getenv("CUEBOT_DB_ENGINE");
if (dbEngine == null) {
return true;
}
DatabaseEngine selectedDatabaseEngine = DatabaseEngine.valueOf(dbEngine.toUpperCase());
return selectedDatabaseEngine.equals(DatabaseEngine.POSTGRES);
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getBeanFactory().getBeanNamesForAnnotation(Bar.class).length > 0) {
return false;
}
return true;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
ConfigurableEnvironment environment = (ConfigurableEnvironment) context
.getEnvironment();
String protocol = environment.getProperty("dubbo.registry.protocol");
if (PROTOCOL.equals(protocol)) {
return ConditionOutcome.noMatch(
"'spring-cloud' protocol was found from 'dubbo.registry.protocol'");
}
String address = environment.getProperty("dubbo.registry.address");
if (StringUtils.startsWithIgnoreCase(address, PROTOCOL)) {
return ConditionOutcome.noMatch(
"'spring-cloud' protocol was found from 'dubbo.registry.address'");
}
Map<String, Object> properties = getSubProperties(
environment.getPropertySources(), "dubbo.registries.");
boolean found = properties.entrySet().stream().anyMatch(entry -> {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
return (key.endsWith(".address") && value.startsWith(PROTOCOL))
|| (key.endsWith(".protocol") && PROTOCOL.equals(value));
});
return found
? ConditionOutcome.noMatch(
"'spring-cloud' protocol was found in 'dubbo.registries.*'")
: ConditionOutcome.match();
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth JWT Condition");
Environment environment = context.getEnvironment();
String keyValue = environment.getProperty("security.oauth2.authorization.jwt.key-value");
if (StringUtils.hasText(keyValue)) {
return ConditionOutcome.match(message.foundExactly("provided private or symmetric key"));
}
return ConditionOutcome.noMatch(message.didNotFind("provided private or symmetric key").atAll());
}
protected Object getParameterByIndex(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Assert.isAssignable(AggregateQueryMethodConditionContext.class, conditionContext.getClass());
AggregateQueryMethodConditionContext ctx = (AggregateQueryMethodConditionContext) conditionContext;
List<Object> parameters = ctx.getParameterValues();
int parameterIndex = getParameterIndex(annotatedTypeMetadata);
int paramCount = parameters.size();
if (parameterIndex < paramCount) {
return parameters.get(parameterIndex);
}
throw new IllegalArgumentException("Argument index " + parameterIndex + " out of bounds, max count: " + paramCount);
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
if (AwsCloudEnvironmentCheckUtils.isRunningOnCloudEnvironment()) {
return ConditionOutcome.match();
}
return ConditionOutcome.noMatch("not running in aws environment");
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(ConditionOnPropertyExists.class.getName());
if (attrs != null) {
Object value = attrs.get("value");
return value != null && null != env && env.getProperty(value.toString()) != null;
}
return false;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (System.getProperty(this.configSystemProperty) != null) {
return ConditionOutcome.match(
startConditionMessage().because("System property '" + this.configSystemProperty + "' is set."));
}
return super.getMatchOutcome(context, metadata);
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage matchMessage = ConditionMessage.empty();
boolean enabled = isSpringSecurityEnabled(context);
if (metadata.isAnnotated(ConditionalOnJuiserSpringSecurityEnabled.class.getName())) {
if (!enabled) {
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(ConditionalOnJuiserSpringSecurityEnabled.class)
.didNotFind("spring security enabled").atAll());
}
matchMessage = matchMessage.andCondition(ConditionalOnJuiserSpringSecurityEnabled.class)
.foundExactly("spring security enabled");
}
if (metadata.isAnnotated(ConditionalOnJuiserSpringSecurityDisabled.class.getName())) {
if (enabled) {
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(ConditionalOnJuiserSpringSecurityDisabled.class)
.didNotFind("spring security disabled").atAll());
}
matchMessage = matchMessage.andCondition(ConditionalOnJuiserSpringSecurityDisabled.class)
.didNotFind("spring security disabled").atAll();
}
return ConditionOutcome.match(matchMessage);
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return AspectUtil.checkClassIfFound(context, CLASS_TO_CHECK, (e) -> logger.info(
"RxJava2 related Aspect extensions are not activated, because RxJava2 is not on the classpath."))
&& AspectUtil.checkClassIfFound(context, R4J_RXJAVA, (e) -> logger.info(
"RxJava2 related Aspect extensions are not activated because Resilience4j RxJava2 module is not on the classpath."));
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
context.getBeanFactory().getBean(RedisTemplate.class);
return false;
} catch (NoSuchBeanDefinitionException e) {
return true;
}
}
@Override
protected boolean matches(ProjectDescription description, ConditionContext context,
AnnotatedTypeMetadata metadata) {
if (description.getPackaging() == null) {
return false;
}
String packagingId = (String) metadata.getAllAnnotationAttributes(ConditionalOnPackaging.class.getName())
.getFirst("value");
Packaging packaging = Packaging.forId(packagingId);
return description.getPackaging().id().equals(packaging.id());
}
@Override
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
return "kafka".equalsIgnoreCase(
env.getProperty("netty.server.interal.communicate"));
}
@Override
public boolean matches( ConditionContext context, AnnotatedTypeMetadata metadata )
{
if ( !isTestRun( context ) )
{
return !getConfiguration().getProperty( ConfigurationKey.REDIS_ENABLED ).equalsIgnoreCase( "true" );
}
return true;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String implVersion = null;
String wicketVersion = retrieveWicketVersion(implVersion);
Map<String, Object> attributes = metadata
.getAnnotationAttributes(ConditionalOnWicket.class.getName());
Range range = (Range) attributes.get("range");
int expectedVersion = (int) attributes.get("value");
String[] splittedWicketVersion = wicketVersion.split("\\.");
int majorWicketVersion = Integer.valueOf(splittedWicketVersion[0]);
return getMatchOutcome(range, majorWicketVersion, expectedVersion);
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Object enablePropertyName = metadata.getAnnotationAttributes(ConditionalOnJdwpDebug.class.getName())
.get(NAME_ENABLE_PROPERTY);
isTrue(nonNull(enablePropertyName) && isNotBlank(enablePropertyName.toString()),
format("%s.%s It shouldn't be empty", ConditionalOnJdwpDebug.class.getSimpleName(), NAME_ENABLE_PROPERTY));
// Obtain environment enable property value.
Boolean enable = context.getEnvironment().getProperty(enablePropertyName.toString(), Boolean.class);
return isNull(enable) ? isJVMDebugging : enable;
}
@Override
protected boolean matches(ProjectDescription description, ConditionContext context,
AnnotatedTypeMetadata metadata) {
Version platformVersion = description.getPlatformVersion();
if (platformVersion == null) {
return false;
}
return Arrays.stream(
(String[]) metadata.getAnnotationAttributes(ConditionalOnPlatformVersion.class.getName()).get("value"))
.anyMatch((range) -> VersionParser.DEFAULT.parseRange(range).match(platformVersion));
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(ConditionalOnClass.class.getName(), true);
String className = String.valueOf(attributes.get(AnnotationUtils.VALUE).get(0));
return ClassUtils.isPresent(className, context.getClassLoader());
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
new CFConfigurationProvider();
} catch (IllegalArgumentException ex) {
LOG.error("Custom Metrics reporter will not start since required ENVs are missing: {}", ex.getMessage());
return false;
}
return true;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth JWT KeyStore Condition");
Environment environment = context.getEnvironment();
String keyStore = environment.getProperty("security.oauth2.authorization.jwt.key-store");
if (StringUtils.hasText(keyStore)) {
return ConditionOutcome.match(message.foundExactly("provided key store location"));
}
return ConditionOutcome.noMatch(message.didNotFind("provided key store location").atAll());
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
}
@Override
protected boolean matches(ProjectDescription description, ConditionContext context,
AnnotatedTypeMetadata metadata) {
if (description.getLanguage() == null) {
return false;
}
String languageId = (String) metadata.getAllAnnotationAttributes(ConditionalOnLanguage.class.getName())
.getFirst("value");
Language language = Language.forId(languageId, null);
return description.getLanguage().id().equals(language.id());
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getEnvironment() != null) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
return true;
}
}
return false;
}
}
return true;
}