下面列出了org.springframework.core.annotation.AnnotationUtils#getValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void assertContextConfigurationLocations() throws Exception {
final ContextConfiguration contextConfig = this.testClass.getAnnotation(ContextConfiguration.class);
final ContextLoader contextLoader = new GenericXmlContextLoader();
final String[] configuredLocations = (String[]) AnnotationUtils.getValue(contextConfig);
final String[] processedLocations = contextLoader.processLocations(this.testClass, configuredLocations);
if (logger.isDebugEnabled()) {
logger.debug("----------------------------------------------------------------------");
logger.debug("Configured locations: " + ObjectUtils.nullSafeToString(configuredLocations));
logger.debug("Expected locations: " + ObjectUtils.nullSafeToString(this.expectedLocations));
logger.debug("Processed locations: " + ObjectUtils.nullSafeToString(processedLocations));
}
assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations,
processedLocations);
}
protected String[] getTargetDestinations(Annotation annotation, Message<?> message, String defaultPrefix) {
if (annotation != null) {
String[] value = (String[]) AnnotationUtils.getValue(annotation);
if (!ObjectUtils.isEmpty(value)) {
return value;
}
}
String name = DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER;
String destination = (String) message.getHeaders().get(name);
if (!StringUtils.hasText(destination)) {
throw new IllegalStateException("No lookup destination header in " + message);
}
return (destination.startsWith("/") ?
new String[] {defaultPrefix + destination} : new String[] {defaultPrefix + "/" + destination});
}
@Test
public void assertContextConfigurationLocations() throws Exception {
final ContextConfiguration contextConfig = this.testClass.getAnnotation(ContextConfiguration.class);
final ContextLoader contextLoader = new GenericXmlContextLoader();
final String[] configuredLocations = (String[]) AnnotationUtils.getValue(contextConfig);
final String[] processedLocations = contextLoader.processLocations(this.testClass, configuredLocations);
if (logger.isDebugEnabled()) {
logger.debug("----------------------------------------------------------------------");
logger.debug("Configured locations: " + ObjectUtils.nullSafeToString(configuredLocations));
logger.debug("Expected locations: " + ObjectUtils.nullSafeToString(this.expectedLocations));
logger.debug("Processed locations: " + ObjectUtils.nullSafeToString(processedLocations));
}
assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations,
processedLocations);
}
@Test
public void assertContextConfigurationLocations() throws Exception {
final ContextConfiguration contextConfig = this.testClass.getAnnotation(ContextConfiguration.class);
final ContextLoader contextLoader = new GenericXmlContextLoader();
final String[] configuredLocations = (String[]) AnnotationUtils.getValue(contextConfig);
final String[] processedLocations = contextLoader.processLocations(this.testClass, configuredLocations);
if (logger.isDebugEnabled()) {
logger.debug("----------------------------------------------------------------------");
logger.debug("Configured locations: " + ObjectUtils.nullSafeToString(configuredLocations));
logger.debug("Expected locations: " + ObjectUtils.nullSafeToString(this.expectedLocations));
logger.debug("Processed locations: " + ObjectUtils.nullSafeToString(processedLocations));
}
assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations,
processedLocations);
}
protected String[] getTargetDestinations(@Nullable Annotation annotation, Message<?> message, String defaultPrefix) {
if (annotation != null) {
String[] value = (String[]) AnnotationUtils.getValue(annotation);
if (!ObjectUtils.isEmpty(value)) {
return value;
}
}
String name = DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER;
String destination = (String) message.getHeaders().get(name);
if (!StringUtils.hasText(destination)) {
throw new IllegalStateException("No lookup destination header in " + message);
}
return (destination.startsWith("/") ?
new String[] {defaultPrefix + destination} : new String[] {defaultPrefix + '/' + destination});
}
/**
* Validate the payload if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid},
* Spring's {@link org.springframework.validation.annotation.Validated},
* and custom annotations whose name starts with "Valid".
* @param message the currently processed message
* @param parameter the method parameter
* @param target the target payload object
* @throws MethodArgumentNotValidException in case of binding errors
*/
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
if (this.validator == null) {
return;
}
for (Annotation ann : parameter.getParameterAnnotations()) {
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
BeanPropertyBindingResult bindingResult =
new BeanPropertyBindingResult(target, getParameterName(parameter));
if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
}
else {
this.validator.validate(target, bindingResult);
}
if (bindingResult.hasErrors()) {
throw new MethodArgumentNotValidException(message, parameter, bindingResult);
}
break;
}
}
}
/**
* Returns the {@link Query} annotation's attribute casted to the given type or default value if no annotation
* available.
*
* @param attribute
* @param type
* @return
*/
private <T> T getAnnotationValue(String attribute, Class<T> type) {
Query annotation = method.getAnnotation(Query.class);
Object value = annotation == null ? AnnotationUtils.getDefaultValue(Query.class, attribute) : AnnotationUtils
.getValue(annotation, attribute);
return type.cast(value);
}
/**
* Validate the model attribute if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid},
* Spring's {@link org.springframework.validation.annotation.Validated},
* and custom annotations whose name starts with "Valid".
* @param binder the DataBinder to be used
* @param methodParam the method parameter
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) {
Annotation[] annotations = methodParam.getParameterAnnotations();
for (Annotation ann : annotations) {
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
binder.validate(validationHints);
break;
}
}
}
private String resolveExpression(A annotation) {
for (String attributeName : EXPRESSION_ATTRIBUTES) {
Object val = AnnotationUtils.getValue(annotation, attributeName);
if (val instanceof String) {
String str = (String) val;
if (!str.isEmpty()) {
return str;
}
}
}
throw new IllegalStateException("Failed to resolve expression: " + annotation);
}
/**
* Check if the given MethodParameter requires validation and if so return
* a (possibly empty) Object[] with validation hints. A return value of
* {@code null} indicates that validation is not required.
*/
@Nullable
private Object[] extractValidationHints(MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation ann : annotations) {
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
return (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
}
}
return null;
}
@Test
public void delete_methodSecured() throws NoSuchMethodException {
Annotation[] annotations = AnnotationUtils.getAnnotations(CommunityServiceImpl.class.getMethod("delete", String.class));
List<Annotation> annotationsList = Arrays.asList(annotations);
Optional<Annotation> securedOpt = annotationsList.stream()
.filter(a -> a.annotationType().isAssignableFrom(Secured.class))
.findFirst();
assertTrue(securedOpt.isPresent());
Annotation securedAnnotation = securedOpt.get();
String[] values = (String[]) AnnotationUtils.getValue(securedAnnotation);
assertTrue(Arrays.asList(values).contains(Role.ADMIN));
assertTrue(Arrays.asList(values).contains(Role.SYSTEM));
}
/**
* 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);
}
private Integer getAnnotationValueAsIntOrNullIfNegative(Annotation annotation, String attributeName) {
Integer timeAllowed = (Integer) AnnotationUtils.getValue(annotation, attributeName);
if (timeAllowed != null && timeAllowed.intValue() > 0) {
return timeAllowed;
}
return null;
}
@SuppressWarnings("unchecked")
private List<String> getAnnotationValuesAsStringList(Annotation annotation, String attribute) {
String[] values = (String[]) AnnotationUtils.getValue(annotation, attribute);
if (values.length > 1 || (values.length == 1 && StringUtils.hasText(values[0]))) {
return CollectionUtils.arrayToList(values);
}
return Collections.emptyList();
}
private String resolveExpression(A annotation) {
for (String attributeName : EXPRESSION_ATTRIBUTES) {
Object val = AnnotationUtils.getValue(annotation, attributeName);
if (val instanceof String) {
String str = (String) val;
if (!str.isEmpty()) {
return str;
}
}
}
throw new IllegalStateException("Failed to resolve expression: " + annotation);
}
/**
* Validate the binding target if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid},
* Spring's {@link org.springframework.validation.annotation.Validated},
* and custom annotations whose name starts with "Valid".
* @param binder the DataBinder to be used
* @param parameter the method parameter descriptor
* @since 4.1.5
* @see #isBindExceptionRequired
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation ann : annotations) {
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
binder.validate(validationHints);
break;
}
}
}
/**
* Validate the model attribute if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid}.
*
* @param binder the DataBinder to be used
* @param parameter the method parameter
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = AnnotationUtils.getValue(annot);
binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
}
}
}
/**
* Validate the binding target if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid},
* Spring's {@link org.springframework.validation.annotation.Validated},
* and custom annotations whose name starts with "Valid".
* @param binder the DataBinder to be used
* @param parameter the method parameter descriptor
* @since 4.1.5
* @see #isBindExceptionRequired
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation ann : annotations) {
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
binder.validate(validationHints);
break;
}
}
}
/**
* Extract the value attribute from the given annotation.
*/
protected Object extractValue(Annotation valueAnnotation) {
Object value = AnnotationUtils.getValue(valueAnnotation);
if (value == null) {
throw new IllegalStateException("Value annotation must have a value attribute");
}
return value;
}
/**
* Default implementation for adapting each of the incoming method arguments using an
* available {@link StreamListenerParameterAdapter} and provide the adapted collection
* of arguments back to the caller.
* @param method annotated with {@link StreamListener}
* @param inboundName inbound binding
* @param applicationContext spring application context
* @param streamListenerParameterAdapters used for adapting the method arguments
* @return adapted incoming arguments
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
default Object[] adaptAndRetrieveInboundArguments(Method method, String inboundName,
ApplicationContext applicationContext,
StreamListenerParameterAdapter... streamListenerParameterAdapters) {
Object[] arguments = new Object[method.getParameterTypes().length];
for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) {
MethodParameter methodParameter = MethodParameter.forExecutable(method,
parameterIndex);
Class<?> parameterType = methodParameter.getParameterType();
Object targetReferenceValue = null;
if (methodParameter.hasParameterAnnotation(Input.class)) {
targetReferenceValue = AnnotationUtils
.getValue(methodParameter.getParameterAnnotation(Input.class));
}
else if (methodParameter.hasParameterAnnotation(Output.class)) {
targetReferenceValue = AnnotationUtils
.getValue(methodParameter.getParameterAnnotation(Output.class));
}
else if (arguments.length == 1 && StringUtils.hasText(inboundName)) {
targetReferenceValue = inboundName;
}
if (targetReferenceValue != null) {
Assert.isInstanceOf(String.class, targetReferenceValue,
"Annotation value must be a String");
Object targetBean = applicationContext
.getBean((String) targetReferenceValue);
// Iterate existing parameter adapters first
for (StreamListenerParameterAdapter streamListenerParameterAdapter : streamListenerParameterAdapters) {
if (streamListenerParameterAdapter.supports(targetBean.getClass(),
methodParameter)) {
arguments[parameterIndex] = streamListenerParameterAdapter
.adapt(targetBean, methodParameter);
break;
}
}
if (arguments[parameterIndex] == null
&& parameterType.isAssignableFrom(targetBean.getClass())) {
arguments[parameterIndex] = targetBean;
}
Assert.notNull(arguments[parameterIndex],
"Cannot convert argument " + parameterIndex + " of " + method
+ "from " + targetBean.getClass() + " to "
+ parameterType);
}
else {
throw new IllegalStateException(
StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS);
}
}
return arguments;
}