下面列出了org.springframework.core.annotation.AnnotationUtils#getAnnotationAttributes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Overrides the default {@link StreamListenerAnnotationBeanPostProcessor}.
*/
@Bean(name = STREAM_LISTENER_ANNOTATION_BEAN_POST_PROCESSOR_NAME)
public static StreamListenerAnnotationBeanPostProcessor streamListenerAnnotationBeanPostProcessor() {
return new StreamListenerAnnotationBeanPostProcessor() {
@Override
protected StreamListener postProcessAnnotation(
StreamListener originalAnnotation, Method annotatedMethod) {
Map<String, Object> attributes = new HashMap<>(
AnnotationUtils.getAnnotationAttributes(originalAnnotation));
attributes.put("condition",
"headers['type']=='" + originalAnnotation.condition() + "'");
return AnnotationUtils.synthesizeAnnotation(attributes,
StreamListener.class, annotatedMethod);
}
};
}
/**
* For a given class, looks for @EmbeddedEntityResource annotations, using the annotation produce
* a Map of the property name key and the entity key
* @return A map of property key name and a value of the entity path name
*/
public static Map<String,Pair<String,Method>> findEmbeddedResources(Class<?> anyClass)
{
Map<String, Pair<String,Method>> embeds = new HashMap<String, Pair<String,Method>>();
List<Method> annotatedMethods = ResourceInspectorUtil.findMethodsByAnnotation(anyClass, EmbeddedEntityResource.class);
if (annotatedMethods != null && !annotatedMethods.isEmpty())
{
for (Method annotatedMethod : annotatedMethods)
{
Annotation annot = AnnotationUtils.findAnnotation(annotatedMethod, EmbeddedEntityResource.class);
if (annot != null)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
String entityPath = findEntityNameByAnnotationAttributes(annotAttribs);
String key = String.valueOf(annotAttribs.get("propertyName"));
embeds.put(key, new Pair<String,Method>(entityPath,annotatedMethod));
}
}
}
return embeds;
}
/**
* Finds operations on an entity
* @param entityPath path to the entity
* @param anyClass resource clause
* @return The operations
*/
private static Map<String,Pair<ResourceOperation,Method>> findOperations(String entityPath, Class<?> anyClass)
{
Map<String, Pair<ResourceOperation,Method>> embeds = new HashMap<String, Pair<ResourceOperation,Method>>();
List<Method> annotatedMethods = ResourceInspectorUtil.findMethodsByAnnotation(anyClass, Operation.class);
if (annotatedMethods != null && !annotatedMethods.isEmpty())
for (Method annotatedMethod : annotatedMethods)
{
//validateOperationMethod(annotatedMethod, anyClass);
Annotation annot = AnnotationUtils.findAnnotation(annotatedMethod, Operation.class);
if (annot != null)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
String actionName = String.valueOf(annotAttribs.get("value"));
String actionPath = ResourceDictionary.propertyResourceKey(entityPath, actionName);
ResourceOperation ro = inspectOperation(anyClass, annotatedMethod, HttpMethod.POST);
embeds.put(actionPath, new Pair<ResourceOperation, Method>(ro, annotatedMethod));
}
}
return embeds;
}
/**
* @param paramAnot Annotation
* @param resource Class<?>
* @param aMethod Method
* @return ResourceParameter
*/
private static ResourceParameter findResourceParameter(Annotation paramAnot, Class<?> resource, Method aMethod)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(paramAnot);
ResourceParameter.KIND paramKind = (ResourceParameter.KIND) annotAttribs.get("kind");
Class<?> dType = String.class;
if (ResourceParameter.KIND.HTTP_BODY_OBJECT.equals(paramKind))
{
dType = ResourceInspectorUtil.determineType(resource, aMethod);
}
return ResourceParameter.valueOf(
String.valueOf(annotAttribs.get("name")),
String.valueOf(annotAttribs.get("title")),
String.valueOf(annotAttribs.get("description")),
(Boolean)annotAttribs.get("required"),
paramKind,
(Boolean)annotAttribs.get("allowMultiple"),
dType);
}
private Annotation synthesizeWithMethodParameterNameAsFallbackValue(
Annotation parameterAnnotation, Method method, int parameterIndex) {
Map<String, Object> annotationAttributes = AnnotationUtils
.getAnnotationAttributes(parameterAnnotation);
Object defaultValue = AnnotationUtils.getDefaultValue(parameterAnnotation);
if (defaultValue instanceof String
&& defaultValue.equals(annotationAttributes.get(AnnotationUtils.VALUE))) {
Type[] parameterTypes = method.getGenericParameterTypes();
String[] parameterNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
if (shouldAddParameterName(parameterIndex, parameterTypes, parameterNames)) {
annotationAttributes.put(AnnotationUtils.VALUE,
parameterNames[parameterIndex]);
}
}
return AnnotationUtils.synthesizeAnnotation(annotationAttributes,
parameterAnnotation.annotationType(), null);
}
/**
* Utility operation to return an array of configuration classes defined in
* {@link EnableBinding} annotation. Typically used for tests that do not rely on
* creating an SCSt boot application annotated with {@link EnableBinding}, yet require
* full {@link Binder} configuration.
* @param additionalConfigurationClasses config classes to be added to the default
* config
* @return an array of configuration classes defined in {@link EnableBinding}
* annotation
*/
public static Class<?>[] getCompleteConfiguration(
Class<?>... additionalConfigurationClasses) {
List<Class<?>> configClasses = new ArrayList<>();
configClasses.add(TestChannelBinderConfiguration.class);
Import annotation = AnnotationUtils.getAnnotation(EnableBinding.class,
Import.class);
Map<String, Object> annotationAttributes = AnnotationUtils
.getAnnotationAttributes(annotation);
configClasses
.addAll(Arrays.asList((Class<?>[]) annotationAttributes.get("value")));
configClasses.add(BindingServiceConfiguration.class);
if (additionalConfigurationClasses != null) {
configClasses.addAll(Arrays.asList(additionalConfigurationClasses));
}
return configClasses.toArray(new Class<?>[] {});
}
/**
* Inspects the method and returns meta data about its operations
* @param aMethod Method
* @param httpMethod HttpMethod
* @return ResourceOperation
*/
public static ResourceOperation inspectOperation(Class<?> resource, Method aMethod, HttpMethod httpMethod)
{
Annotation annot = AnnotationUtils.findAnnotation(aMethod, WebApiDescription.class);
List<ResourceParameter> parameters = new ArrayList<ResourceParameter>();
parameters.addAll(inspectParameters(resource, aMethod, httpMethod));
if (annot != null)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
String title = String.valueOf(annotAttribs.get("title"));
String desc = String.valueOf(annotAttribs.get("description"));
Integer success = (Integer) annotAttribs.get("successStatus");
return new ResourceOperation(httpMethod, title, desc, parameters, validSuccessCode(httpMethod,success));
}
else {
return new ResourceOperation(httpMethod,
"Missing @WebApiDescription annotation",
"This method should be annotated with @WebApiDescription", parameters, validSuccessCode(httpMethod, ResourceOperation.UNSET_STATUS));
}
}
private String formatAnnotation(Annotation annotation) {
Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
map.forEach((key, value) -> {
if (value.equals(DEFAULT_VALUE_NONE)) {
map.put(key, "NONE");
}
});
return annotation.annotationType().getName() + map;
}
private String formatAnnotation(Annotation annotation) {
Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
map.forEach((key, value) -> {
if (value.equals(DEFAULT_VALUE_NONE)) {
map.put(key, "NONE");
}
});
return annotation.annotationType().getName() + map;
}
public static String getBindingTargetName(Annotation annotation, Method method) {
Map<String, Object> attrs = AnnotationUtils.getAnnotationAttributes(annotation,
false);
if (attrs.containsKey("value")
&& StringUtils.hasText((CharSequence) attrs.get("value"))) {
return (String) attrs.get("value");
}
return method.getName();
}
/**
* Construct a {@code MergedSqlConfig} instance by merging the configuration
* from the supplied local (potentially method-level) {@code @SqlConfig} annotation
* with class-level configuration discovered on the supplied {@code testClass}.
* <p>Local configuration overrides class-level configuration.
* <p>If the test class is not annotated with {@code @SqlConfig}, no merging
* takes place and the local configuration is used "as is".
*/
MergedSqlConfig(SqlConfig localSqlConfig, Class<?> testClass) {
Assert.notNull(localSqlConfig, "Local @SqlConfig must not be null");
Assert.notNull(testClass, "testClass must not be null");
// Get global attributes, if any.
AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
testClass, SqlConfig.class.getName(), false, false);
// Override global attributes with local attributes.
if (attributes != null) {
for (String key : attributes.keySet()) {
Object value = AnnotationUtils.getValue(localSqlConfig, key);
if (value != null) {
// Is the value explicit (i.e., not a 'default')?
if (!value.equals("") && value != TransactionMode.DEFAULT && value != ErrorMode.DEFAULT) {
attributes.put(key, value);
}
}
}
}
else {
// Otherwise, use local attributes only.
attributes = AnnotationUtils.getAnnotationAttributes(localSqlConfig, false, false);
}
this.dataSource = attributes.getString("dataSource");
this.transactionManager = attributes.getString("transactionManager");
this.transactionMode = getEnum(attributes, "transactionMode", TransactionMode.DEFAULT, TransactionMode.INFERRED);
this.encoding = attributes.getString("encoding");
this.separator = getString(attributes, "separator", ScriptUtils.DEFAULT_STATEMENT_SEPARATOR);
this.commentPrefix = getString(attributes, "commentPrefix", ScriptUtils.DEFAULT_COMMENT_PREFIX);
this.blockCommentStartDelimiter = getString(attributes, "blockCommentStartDelimiter",
ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER);
this.blockCommentEndDelimiter = getString(attributes, "blockCommentEndDelimiter",
ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER);
this.errorMode = getEnum(attributes, "errorMode", ErrorMode.DEFAULT, ErrorMode.FAIL_ON_ERROR);
}
/**
* Finds the name of the entity using its annotation.
* @param entityAnnot EntityResource
* @return the entity name/path
*/
protected static String findEntityName(EntityResource entityAnnot)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(entityAnnot);
String urlPath = String.valueOf(annotAttribs.get("name"));
return urlPath;
}
protected Annotation synthesizeWithMethodParameterNameAsFallbackValue(Annotation parameterAnnotation, Method method,
int parameterIndex) {
Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(parameterAnnotation);
Object defaultValue = AnnotationUtils.getDefaultValue(parameterAnnotation);
if (defaultValue instanceof String && defaultValue.equals(annotationAttributes.get(AnnotationUtils.VALUE))) {
Type[] parameterTypes = method.getGenericParameterTypes();
String[] parameterNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
if (shouldAddParameterName(parameterIndex, parameterTypes, parameterNames)) {
annotationAttributes.put(AnnotationUtils.VALUE, parameterNames[parameterIndex]);
}
}
return AnnotationUtils.synthesizeAnnotation(annotationAttributes, parameterAnnotation.annotationType(), null);
}
/**
* Finds the property name that is used as the unique id.
* @param uniqueIdMethod Method
* @return String the property name that is used as the unique id.
*/
public static String findUniqueIdName(Method uniqueIdMethod)
{
Annotation annot = AnnotationUtils.findAnnotation(uniqueIdMethod, UniqueId.class);
if (annot != null)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
String uniqueIdName = String.valueOf(annotAttribs.get("name"));
return uniqueIdName;
}
return UniqueId.UNIQUE_NAME;
}
@Test
public void test(){
AnnotationTest inst = AnnotationUtils.getAnnotation(AnnotationUtilsTest.class, AnnotationTest.class);
Map<String, Object> attrs = AnnotationUtils.getAnnotationAttributes(inst);
System.out.println("attrs:"+attrs);
Assert.assertEquals("test", attrs.get("name"));
}
/**
* Match the given qualifier annotation against the candidate bean definition.
*/
protected boolean checkQualifier(
BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {
Class<? extends Annotation> type = annotation.annotationType();
RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();
AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
if (qualifier == null) {
qualifier = bd.getQualifier(ClassUtils.getShortName(type));
}
if (qualifier == null) {
// First, check annotation on factory method, if applicable
Annotation targetAnnotation = getFactoryMethodAnnotation(bd, type);
if (targetAnnotation == null) {
RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
if (dbd != null) {
targetAnnotation = getFactoryMethodAnnotation(dbd, type);
}
}
if (targetAnnotation == null) {
// Look for matching annotation on the target class
if (getBeanFactory() != null) {
try {
Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
if (beanType != null) {
targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Not the usual case - simply forget about the type check...
}
}
if (targetAnnotation == null && bd.hasBeanClass()) {
targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
}
}
if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
return true;
}
}
Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
if (attributes.isEmpty() && qualifier == null) {
// If no attributes, the qualifier must be present
return false;
}
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
String attributeName = entry.getKey();
Object expectedValue = entry.getValue();
Object actualValue = null;
// Check qualifier first
if (qualifier != null) {
actualValue = qualifier.getAttribute(attributeName);
}
if (actualValue == null) {
// Fall back on bean definition attribute
actualValue = bd.getAttribute(attributeName);
}
if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
// Fall back on bean name (or alias) match
continue;
}
if (actualValue == null && qualifier != null) {
// Fall back on default, but only if the qualifier is present
actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
}
if (actualValue != null) {
actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
}
if (!expectedValue.equals(actualValue)) {
return false;
}
}
return true;
}
public AnnotationAttributes getAnnotationAttributes(Class<? extends Annotation> annotationClass){
Assert.notNull(annotationClass, "annotationClass can not be null");
Annotation anno = getParameterAnnotation(annotationClass);
return AnnotationUtils.getAnnotationAttributes(null, anno);
}
/**
* Match the given qualifier annotation against the candidate bean definition.
*/
protected boolean checkQualifier(
BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {
Class<? extends Annotation> type = annotation.annotationType();
RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();
AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
if (qualifier == null) {
qualifier = bd.getQualifier(ClassUtils.getShortName(type));
}
if (qualifier == null) {
// First, check annotation on factory method, if applicable
Annotation targetAnnotation = getFactoryMethodAnnotation(bd, type);
if (targetAnnotation == null) {
RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
if (dbd != null) {
targetAnnotation = getFactoryMethodAnnotation(dbd, type);
}
}
if (targetAnnotation == null) {
// Look for matching annotation on the target class
if (getBeanFactory() != null) {
Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
if (beanType != null) {
targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
}
}
if (targetAnnotation == null && bd.hasBeanClass()) {
targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
}
}
if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
return true;
}
}
Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
if (attributes.isEmpty() && qualifier == null) {
// If no attributes, the qualifier must be present
return false;
}
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
String attributeName = entry.getKey();
Object expectedValue = entry.getValue();
Object actualValue = null;
// Check qualifier first
if (qualifier != null) {
actualValue = qualifier.getAttribute(attributeName);
}
if (actualValue == null) {
// Fall back on bean definition attribute
actualValue = bd.getAttribute(attributeName);
}
if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
// Fall back on bean name (or alias) match
continue;
}
if (actualValue == null && qualifier != null) {
// Fall back on default, but only if the qualifier is present
actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
}
if (actualValue != null) {
actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
}
if (!expectedValue.equals(actualValue)) {
return false;
}
}
return true;
}
/**
* Inspects the Method to find any @WebApiParameters and @WebApiParam
* @param resource the class
* @param aMethod the method
* @param httpMethod HttpMethod
* @return a List of parameters
*/
private static List<ResourceParameter> inspectParameters(Class<?> resource, Method aMethod, HttpMethod httpMethod)
{
List<ResourceParameter> params = new ArrayList<ResourceParameter>();
Annotation annot = AnnotationUtils.findAnnotation(aMethod, WebApiParameters.class);
if (annot != null)
{
Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
WebApiParam[] apiParams = (WebApiParam[]) annotAttribs.get("value");
for (int i = 0; i < apiParams.length; i++)
{
params.add(findResourceParameter(apiParams[i], resource, aMethod));
}
}
else
{
Annotation paramAnot = AnnotationUtils.findAnnotation(aMethod, WebApiParam.class);
if (paramAnot!=null)
{
params.add(findResourceParameter(paramAnot, resource, aMethod));
}
}
//Setup default parameters
switch(httpMethod)
{
case POST:
if (paramsCount(params,ResourceParameter.KIND.URL_PATH) == 0)
{
params.add(ResourceParameter.ENTITY_PARAM);
}
if (paramsCount(params,ResourceParameter.KIND.HTTP_BODY_OBJECT) == 0)
{
inspectBodyParamAndReturnType(resource, aMethod, params);
}
break;
case PUT:
int urlPathForPut = paramsCount(params,ResourceParameter.KIND.URL_PATH);
if (urlPathForPut == 0)
{
params.add(ResourceParameter.ENTITY_PARAM);
}
if (RelationshipResourceAction.Update.class.isAssignableFrom(resource) && urlPathForPut <2)
{
params.add(ResourceParameter.RELATIONSHIP_PARAM);
}
if (paramsCount(params,ResourceParameter.KIND.HTTP_BODY_OBJECT)== 0)
{
inspectBodyParamAndReturnType(resource, aMethod, params);
}
break;
case GET:
int urlPathForGet = paramsCount(params,ResourceParameter.KIND.URL_PATH);
if (urlPathForGet == 0 && (EntityResourceAction.ReadById.class.isAssignableFrom(resource) && READ_BY_ID_METHODNAME.equals(aMethod.getName())))
{
params.add(ResourceParameter.ENTITY_PARAM);
}
else if (RelationshipResourceAction.ReadById.class.isAssignableFrom(resource)||RelationshipResourceAction.Read.class.isAssignableFrom(resource))
{
//Its a RelationshipResourceAction
if (urlPathForGet == 0)
{
params.add(ResourceParameter.ENTITY_PARAM);
}
//This method is what we are inspecting not what the class implements.
if (READ_BY_ID_METHODNAME.equals(aMethod.getName()) && urlPathForGet< 2)
{
params.add(ResourceParameter.RELATIONSHIP_PARAM);
}
}
if (!READ_BY_ID_METHODNAME.equals(aMethod.getName()))
{
params.add(ResourceParameter.SKIP_PARAM);
params.add(ResourceParameter.MAX_ITEMS_PARAM);
params.add(ResourceParameter.PROPS_PARAM);
}
break;
case DELETE:
int urlPathForDelete = paramsCount(params,ResourceParameter.KIND.URL_PATH);
if (urlPathForDelete == 0)
{
params.add(ResourceParameter.ENTITY_PARAM);
}
//Add relationship param ?
if (RelationshipResourceAction.Delete.class.isAssignableFrom(resource) && urlPathForDelete <2)
{
params.add(ResourceParameter.RELATIONSHIP_PARAM);
}
}
return params;
}
/**
* Resolve placeholders in specified {@link Annotation annotation}
*
* @param annotation {@link Annotation annotation}
* @return Resolved {@link Properties source properties}
*/
public Properties resolve(Annotation annotation) {
Map<String, Object> attributes = AnnotationUtils
.getAnnotationAttributes(annotation);
return resolve(attributes);
}