Skip to content

Commit

Permalink
Introduce @ConditionalOnMissingServletFilter
Browse files Browse the repository at this point in the history
This commit introduces a new Conditional annotation
`@ConditionalOnMissingServletFilter` which checks for the absence of
Servlet filters as beans or `FilterRegistrationBean`s.

This Conditional annotation can be used to guard Servlet Filter bean
definitions like:

```
@bean
@ConditionalOnMissingServletFilter
public MyServletFilter myServletFilter() {
  //...
}
```

Fixes spring-projectsgh-7475
  • Loading branch information
bclozel committed Dec 15, 2016
1 parent 0fbe56e commit 44ada77
Show file tree
Hide file tree
Showing 3 changed files with 434 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.condition;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Conditional;

/**
* {@link Conditional} that only matches when the specified servlet filter types
* are not contained in the {@link org.springframework.beans.factory.BeanFactory},
* either registered directly as beans or registered with
* {@link org.springframework.boot.web.servlet.FilterRegistrationBean}.
* <p>
* The condition can only match the bean definitions that have been processed by the
* application context so far and, as such, it is strongly recommended to use this
* condition on auto-configuration classes only. If a candidate bean may be created by
* another auto-configuration, make sure that the one using this condition runs after.
*
* @author Brian Clozel
* @since 1.5.0
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnMissingServletFilterCondition.class)
public @interface ConditionalOnMissingServletFilter {

/**
* The class type of servlet filter bean that should be checked.
* The condition matches when each class specified is missing in the
* {@link org.springframework.context.ApplicationContext}.
* @return the class types of beans to check
*/
Class<?>[] value() default {};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.condition;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.ConfigurationCondition;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

/**
* {@link Condition} that checks for the absence of specific Servlet Filters.
* @author Brian Clozel
* @since 1.5.0
*/
@Order(Ordered.LOWEST_PRECEDENCE)
public class OnMissingServletFilterCondition extends SpringBootCondition implements ConfigurationCondition {

@Override
public ConfigurationPhase getConfigurationPhase() {
return ConfigurationPhase.REGISTER_BEAN;
}

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage matchMessage = ConditionMessage.empty();
if (metadata.isAnnotated(ConditionalOnMissingServletFilter.class.getName())) {
List<String> servletFilters = parseAnnotationForServletFilters(context, metadata);
Set<String> matching = getMatchingBeans(context, servletFilters);
if (matching.isEmpty()) {
return ConditionOutcome.match(ConditionMessage
.forCondition(ConditionalOnMissingServletFilter.class)
.didNotFind("any Servlet filter").atAll());
}
else {
return ConditionOutcome.noMatch(ConditionMessage
.forCondition(ConditionalOnMissingServletFilter.class)
.found("servlet filter", "servlet filters")
.items(ConditionMessage.Style.QUOTE, matching));
}
}
return ConditionOutcome.match(matchMessage);
}

private List<String> parseAnnotationForServletFilters(ConditionContext context, AnnotatedTypeMetadata metadata) {
List<String> servletFilters = new ArrayList<String>();
String annotationType = ConditionalOnMissingServletFilter.class.getName();
List<Object> values = metadata
.getAllAnnotationAttributes(annotationType, true).get("value");
if (values != null) {
for (Object value : values) {
if (value instanceof String[]) {
Collections.addAll(servletFilters, (String[]) value);
}
else {
servletFilters.add((String) value);
}
}
}
if (servletFilters.isEmpty() &&
metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName())) {
addDeducedBeanTypeForBeanMethod(context, metadata, servletFilters, (MethodMetadata) metadata);
}
if (servletFilters.isEmpty()) {
throw new IllegalStateException("@ConditionalOnMissingServletFilter must specify at least one type" +
"or should be declared on a @Bean method defining an Servlet Filter");
}
return servletFilters;
}

private void addDeducedBeanTypeForBeanMethod(ConditionContext context,
AnnotatedTypeMetadata metadata, final List<String> beanTypes,
final MethodMetadata methodMetadata) {
try {
// We should be safe to load at this point since we are in the
// REGISTER_BEAN phase
Class<?> configClass = ClassUtils.forName(
methodMetadata.getDeclaringClassName(), context.getClassLoader());
ReflectionUtils.doWithMethods(configClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method)
throws IllegalArgumentException, IllegalAccessException {
if (methodMetadata.getMethodName().equals(method.getName())) {
Assert.state(ClassUtils.isAssignable(Filter.class, method.getReturnType())
|| ClassUtils.isAssignable(FilterRegistrationBean.class, method.getReturnType()),
"Type " + method.getReturnType().getName() +
" returned by " + methodMetadata.getDeclaringClassName() + "."
+ methodMetadata.getMethodName() + " is not a Servlet Filter");
beanTypes.add(method.getReturnType().getName());
}
}
});
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Could not deduce Bean type returned by "
+ methodMetadata.getDeclaringClassName() + "."
+ methodMetadata.getMethodName(), ex);
}
}

private Set<String> getMatchingBeans(ConditionContext context, List<String> servletFilters) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
if (beanFactory == null) {
return Collections.emptySet();
}
Set<String> result = new LinkedHashSet<String>();
BeanTypeRegistry beanTypeRegistry = BeanTypeRegistry.get(context.getBeanFactory());
try {
Map<String, FilterRegistrationBean> filterRegistrations = context
.getBeanFactory().getBeansOfType(FilterRegistrationBean.class);
for (String servletFilter : servletFilters) {
// checking for servlet filter beans
Class<?> filterType = ClassUtils.forName(servletFilter, context.getClassLoader());
result.addAll(beanTypeRegistry.getNamesForType(filterType));
// checking for servlet filter registrations
for (Map.Entry<String, FilterRegistrationBean> entry : filterRegistrations.entrySet()) {
FilterRegistrationBean registrationBean = entry.getValue();
if (ClassUtils.isAssignableValue(filterType, registrationBean.getFilter())) {
result.add(entry.getKey());
}
}
}
}
catch (Throwable e) {
return Collections.emptySet();
}
return result;
}

}
Loading

0 comments on commit 44ada77

Please sign in to comment.