Introduce FeatureSpecification support

Introduce FeatureSpecification interface and implementations

    FeatureSpecification objects decouple the configuration of
    spring container features from the concern of parsing XML
    namespaces, allowing for reuse in code-based configuration
    (see @Feature* annotations below).

    * ComponentScanSpec
    * TxAnnotationDriven
    * MvcAnnotationDriven
    * MvcDefaultServletHandler
    * MvcResources
    * MvcViewControllers

Refactor associated BeanDefinitionParsers to delegate to new impls above

    The following BeanDefinitionParser implementations now deal only
    with the concern of XML parsing.  Validation is handled by their
    corresponding FeatureSpecification object.  Bean definition creation
    and registration is handled by their corresponding
    FeatureSpecificationExecutor type.

    * ComponentScanBeanDefinitionParser
    * AnnotationDrivenBeanDefinitionParser (tx)
    * AnnotationDrivenBeanDefinitionParser (mvc)
    * DefaultServletHandlerBeanDefinitionParser
    * ResourcesBeanDefinitionParser
    * ViewControllerBeanDefinitionParser

Update AopNamespaceUtils to decouple from XML (DOM API)

    Methods necessary for executing TxAnnotationDriven specification
    (and eventually, the AspectJAutoProxy specification) have been
    added that accept boolean arguments for whether to proxy
    target classes and whether to expose the proxy via threadlocal.

    Methods that accepted and introspected DOM Element objects still
    exist but have been deprecated.

Introduce @FeatureConfiguration classes and @Feature methods

    Allow for creation and configuration of FeatureSpecification objects
    at the user level.  A companion for @Configuration classes allowing
    for completely code-driven configuration of the Spring container.

    See changes in ConfigurationClassPostProcessor for implementation
    details.

    See Feature*Tests for usage examples.

    FeatureTestSuite in .integration-tests is a JUnit test suite designed
    to aggregate all BDP and Feature* related tests for a convenient way
    to confirm that Feature-related changes don't break anything.
    Uncomment this test and execute from Eclipse / IDEA. Due to classpath
    issues, this cannot be compiled by Ant/Ivy at the command line.

Introduce @FeatureAnnotation meta-annotation and @ComponentScan impl

    @FeatureAnnotation provides an alternate mechanism for creating
    and executing FeatureSpecification objects.  See @ComponentScan
    and its corresponding ComponentScanAnnotationParser implementation
    for details.  See ComponentScanAnnotationIntegrationTests for usage
    examples

Introduce Default[Formatting]ConversionService implementations

    Allows for convenient instantiation of ConversionService objects
    containing defaults appropriate for most environments.  Replaces
    similar support originally in ConversionServiceFactory (which is now
    deprecated). This change was justified by the need to avoid use
    of FactoryBeans in @Configuration classes (such as
    FormattingConversionServiceFactoryBean). It is strongly preferred
    that users simply instantiate and configure the objects that underlie
    our FactoryBeans. In the case of the ConversionService types, the
    easiest way to do this is to create Default* subtypes. This also
    follows convention with the rest of the framework.

Minor updates to util classes

    All in service of changes above. See diffs for self-explanatory
    details.

    * BeanUtils
    * ObjectUtils
    * ReflectionUtils
This commit is contained in:
Chris Beams
2011-02-08 14:42:33 +00:00
parent b04987ccc3
commit b4fea47d5c
127 changed files with 7397 additions and 1132 deletions

View File

@@ -64,8 +64,15 @@ public class AnnotationDrivenBeanDefinitionParserTests {
@Test
public void testMessageConverters() {
loadBeanDefinitions("mvc-config-message-converters.xml");
verifyMessageConverters(appContext.getBean(AnnotationMethodHandlerAdapter.class));
verifyMessageConverters(appContext.getBean(AnnotationMethodHandlerExceptionResolver.class));
verifyMessageConverters(appContext.getBean(AnnotationMethodHandlerAdapter.class), true);
verifyMessageConverters(appContext.getBean(AnnotationMethodHandlerExceptionResolver.class), true);
}
@Test
public void testMessageConvertersWithoutDefaultRegistrations() {
loadBeanDefinitions("mvc-config-message-converters-defaults-off.xml");
verifyMessageConverters(appContext.getBean(AnnotationMethodHandlerAdapter.class), false);
verifyMessageConverters(appContext.getBean(AnnotationMethodHandlerExceptionResolver.class), false);
}
@Test
@@ -88,12 +95,18 @@ public class AnnotationDrivenBeanDefinitionParserTests {
appContext.refresh();
}
private void verifyMessageConverters(Object bean) {
private void verifyMessageConverters(Object bean, boolean hasDefaultRegistrations) {
assertNotNull(bean);
Object converters = new DirectFieldAccessor(bean).getPropertyValue("messageConverters");
assertNotNull(converters);
assertTrue(converters instanceof HttpMessageConverter<?>[]);
assertEquals(2, ((HttpMessageConverter<?>[]) converters).length);
if (hasDefaultRegistrations) {
assertTrue("Default converters are registered in addition to custom ones",
((HttpMessageConverter<?>[]) converters).length > 2);
} else {
assertTrue("Default converters should not be registered",
((HttpMessageConverter<?>[]) converters).length == 2);
}
assertTrue(((HttpMessageConverter<?>[]) converters)[0] instanceof StringHttpMessageConverter);
assertTrue(((HttpMessageConverter<?>[]) converters)[1] instanceof ResourceHttpMessageConverter);
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2011 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.web.servlet.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Feature;
import org.springframework.context.annotation.FeatureConfiguration;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
/**
* Integration tests for the {@link MvcAnnotationDriven} feature specification.
* @author Rossen Stoyanchev
* @author Chris Beams
* @since 3.1
*/
public class MvcAnnotationDrivenFeatureTests {
@Test
public void testMessageCodesResolver() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MvcFeature.class, MvcBeans.class);
ctx.refresh();
AnnotationMethodHandlerAdapter adapter = ctx.getBean(AnnotationMethodHandlerAdapter.class);
assertNotNull(adapter);
Object initializer = new DirectFieldAccessor(adapter).getPropertyValue("webBindingInitializer");
assertNotNull(initializer);
MessageCodesResolver resolver = ((ConfigurableWebBindingInitializer) initializer).getMessageCodesResolver();
assertNotNull(resolver);
assertEquals("test.foo.bar", resolver.resolveMessageCodes("foo", "bar")[0]);
Object argResolvers = new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
assertNotNull(argResolvers);
WebArgumentResolver[] argResolversArray = (WebArgumentResolver[]) argResolvers;
assertEquals(1, argResolversArray.length);
assertTrue(argResolversArray[0] instanceof TestWebArgumentResolver);
Object converters = new DirectFieldAccessor(adapter).getPropertyValue("messageConverters");
assertNotNull(converters);
HttpMessageConverter<?>[] convertersArray = (HttpMessageConverter<?>[]) converters;
assertTrue("Default converters are registered in addition to the custom one", convertersArray.length > 1);
assertTrue(convertersArray[0] instanceof StringHttpMessageConverter);
}
}
@FeatureConfiguration
class MvcFeature {
@Feature
public MvcAnnotationDriven annotationDriven(MvcBeans mvcBeans) {
return new MvcAnnotationDriven()
.conversionService(mvcBeans.conversionService())
.messageCodesResolver(mvcBeans.messageCodesResolver())
.validator(mvcBeans.validator())
.messageConverters(new StringHttpMessageConverter())
.argumentResolvers(new TestWebArgumentResolver());
}
}
@Configuration
class MvcBeans {
@Bean
public FormattingConversionService conversionService() {
return new DefaultFormattingConversionService();
}
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
@Bean MessageCodesResolver messageCodesResolver() {
return new TestMessageCodesResolver();
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2011 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.web.servlet.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Feature;
import org.springframework.context.annotation.FeatureConfiguration;
import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
/**
* Test fixture for {@link MvcDefaultServletHandler} feature specification.
* @author Rossen Stoyanchev
* @since 3.1
*/
public class MvcDefaultServletHandlerTests {
@Test
public void testDefaultServletHandler() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MvcDefaultServletHandlerFeature.class);
ctx.refresh();
HttpRequestHandlerAdapter adapter = ctx.getBean(HttpRequestHandlerAdapter.class);
assertNotNull(adapter);
DefaultServletHttpRequestHandler handler = ctx.getBean(DefaultServletHttpRequestHandler.class);
assertNotNull(handler);
String defaultServletHandlerName = (String) new DirectFieldAccessor(handler)
.getPropertyValue("defaultServletName");
assertEquals("foo", defaultServletHandlerName);
}
@FeatureConfiguration
private static class MvcDefaultServletHandlerFeature {
@SuppressWarnings("unused")
@Feature
public MvcDefaultServletHandler defaultServletHandler() {
return new MvcDefaultServletHandler("foo");
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2011 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.web.servlet.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Feature;
import org.springframework.context.annotation.FeatureConfiguration;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
/**
* Test fixture for {@link MvcResources} feature specification.
* @author Rossen Stoyanchev
* @since 3.1
*/
public class MvcResourcesTests {
@Test
public void testResources() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MvcResourcesFeature.class);
ctx.refresh();
HttpRequestHandlerAdapter adapter = ctx.getBean(HttpRequestHandlerAdapter.class);
assertNotNull(adapter);
ResourceHttpRequestHandler handler = ctx.getBean(ResourceHttpRequestHandler.class);
assertNotNull(handler);
@SuppressWarnings("unchecked")
List<Resource> locations = (List<Resource>) new DirectFieldAccessor(handler).getPropertyValue("locations");
assertNotNull(locations);
assertEquals(2, locations.size());
assertEquals("foo", locations.get(0).getFilename());
assertEquals("bar", locations.get(1).getFilename());
SimpleUrlHandlerMapping mapping = ctx.getBean(SimpleUrlHandlerMapping.class);
assertEquals(1, mapping.getOrder());
assertSame(handler, mapping.getHandlerMap().get("/resources/**"));
}
@Test
public void testInvalidResources() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(InvalidMvcResourcesFeature.class);
try {
ctx.refresh();
fail("Invalid feature spec should not validate");
} catch (RuntimeException e) {
assertTrue(e.getCause().getMessage().contains("Mapping is required"));
// TODO : should all problems be in the message ?
}
}
@FeatureConfiguration
private static class MvcResourcesFeature {
@SuppressWarnings("unused")
@Feature
public MvcResources resources() {
return new MvcResources("/resources/**", new String[] { "/foo", "/bar" }).cachePeriod(86400).order(1);
}
}
@FeatureConfiguration
private static class InvalidMvcResourcesFeature {
@SuppressWarnings("unused")
@Feature
public MvcResources resources() {
return new MvcResources(" ", new String[] {});
}
}
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright 2002-2011 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.web.servlet.config;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Feature;
import org.springframework.context.annotation.FeatureConfiguration;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
/**
* Test fixture for {@link MvcViewControllers} feature specification.
* @author Rossen Stoyanchev
* @since 3.1
*/
public class MvcViewControllersTests {
@Test
public void testMvcViewControllers() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MvcViewControllersFeature.class);
ctx.refresh();
SimpleControllerHandlerAdapter adapter = ctx.getBean(SimpleControllerHandlerAdapter.class);
assertNotNull(adapter);
SimpleUrlHandlerMapping handler = ctx.getBean(SimpleUrlHandlerMapping.class);
assertNotNull(handler);
Map<String, ?> urlMap = handler.getUrlMap();
assertNotNull(urlMap);
assertEquals(2, urlMap.size());
ParameterizableViewController controller = (ParameterizableViewController) urlMap.get("/");
assertNotNull(controller);
assertEquals("home", controller.getViewName());
controller = (ParameterizableViewController) urlMap.get("/account");
assertNotNull(controller);
assertNull(controller.getViewName());
}
@Test
public void testEmptyPath() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(EmptyPathViewControllersFeature.class);
try {
ctx.refresh();
fail("expected exception");
} catch (Exception ex) {
assertTrue(ex.getCause().getMessage().contains("path attribute"));
}
}
@Test
public void testEmptyViewName() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(EmptyViewNameViewControllersFeature.class);
try {
ctx.refresh();
fail("expected exception");
} catch (Exception ex) {
assertTrue(ex.getCause().getMessage().contains("not empty"));
}
}
@Test
public void testNullViewName() {
FailFastProblemReporter problemReporter = new FailFastProblemReporter();
assertThat(new MvcViewControllers("/some/path").validate(problemReporter), is(true));
}
@FeatureConfiguration
private static class MvcViewControllersFeature {
@SuppressWarnings("unused")
@Feature
public MvcViewControllers mvcViewControllers() {
return new MvcViewControllers("/", "home").viewController("/account");
}
}
@FeatureConfiguration
private static class EmptyViewNameViewControllersFeature {
@SuppressWarnings("unused")
@Feature
public MvcViewControllers mvcViewControllers() {
return new MvcViewControllers("/some/path", "");
}
}
@FeatureConfiguration
private static class EmptyPathViewControllersFeature {
@SuppressWarnings("unused")
@Feature
public MvcViewControllers mvcViewControllers() {
return new MvcViewControllers("", "someViewName");
}
}
}

View File

@@ -1,10 +1,26 @@
/*
* Copyright 2002-2011 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.web.servlet.mvc.annotation;
import java.awt.Color;
import org.junit.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -16,7 +32,7 @@ public class Spr7766Tests {
public void test() throws Exception {
AnnotationMethodHandlerAdapter adapter = new AnnotationMethodHandlerAdapter();
ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer();
GenericConversionService service = ConversionServiceFactory.createDefaultConversionService();
GenericConversionService service = new DefaultConversionService();
service.addConverter(new ColorConverter());
binder.setConversionService(service);
adapter.setWebBindingInitializer(binder);

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2002-2011 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.web.servlet.mvc.annotation;
import static org.junit.Assert.assertEquals;
@@ -9,7 +25,7 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -30,7 +46,7 @@ public class Spr7839Tests {
@Before
public void setUp() {
ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer();
GenericConversionService service = ConversionServiceFactory.createDefaultConversionService();
GenericConversionService service = new DefaultConversionService();
service.addConverter(new Converter<String, NestedBean>() {
public NestedBean convert(String source) {
return new NestedBean(source);

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>