From b6a3701ced496cb074d18edf6cb81cdd4b4e5796 Mon Sep 17 00:00:00 2001 From: Jeff Scott Brown Date: Mon, 16 Sep 2013 11:06:49 -0500 Subject: [PATCH] GRAILS-5779 - start removing bean builder code Use the corresponding library provided by Spring 4 --- .../groovy/grails/spring/WebBeanBuilder.java | 10 +- .../spring/GrailsRuntimeConfigurator.java | 10 +- .../spring/GrailsWebApplicationContext.java | 15 +- .../spring/WebRuntimeSpringConfiguration.java | 1 + .../plugins/AbstractGrailsPluginManager.java | 2 +- .../grails/plugins/CoreGrailsPlugin.groovy | 4 +- .../grails/plugins/DefaultGrailsPlugin.java | 10 +- .../groovy/grails/plugins/GrailsPlugin.java | 2 +- .../grails/plugins/GrailsPluginManager.java | 2 +- .../plugins/ProfilingGrailsPluginManager.java | 3 +- .../project/loader/GrailsProjectLoader.groovy | 11 +- ...lderConfigurerCorePluginRuntimeSpec.groovy | 7 +- .../GrailsPlaceholderConfigurerSpec.groovy | 9 +- .../mixin/support/GrailsUnitTestMixin.groovy | 4 +- .../groovy/grails/spring/BeanBuilder.java | 975 ------------------ .../grails/spring/DynamicElementReader.groovy | 148 --- .../commons/spring/BeanConfiguration.java | 141 --- .../spring/DefaultBeanConfiguration.java | 308 ------ .../DefaultRuntimeSpringConfiguration.java | 366 ------- .../spring/RuntimeSpringConfiguration.java | 235 ----- ...ransactionManagerPostProcessorTests.groovy | 5 +- .../grails/spring/BeanBuilderTests.groovy | 934 ----------------- .../spring/DynamicElementReaderTests.groovy | 23 - .../GrailsRuntimeConfiguratorTests.java | 3 + .../plugins/DefaultGrailsPluginTests.java | 8 +- .../DataSourceGrailsPluginTests.groovy | 6 +- .../web/ControllersGrailsPluginTests.groovy | 7 +- .../SpringProxiedBeanReloadTests.groovy | 8 +- .../groovy/grails/gsp/PageRendererSpec.groovy | 5 +- 29 files changed, 73 insertions(+), 3189 deletions(-) delete mode 100644 grails-spring/src/main/groovy/grails/spring/BeanBuilder.java delete mode 100644 grails-spring/src/main/groovy/grails/spring/DynamicElementReader.groovy delete mode 100644 grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/BeanConfiguration.java delete mode 100644 grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultBeanConfiguration.java delete mode 100644 grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultRuntimeSpringConfiguration.java delete mode 100644 grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/RuntimeSpringConfiguration.java delete mode 100644 grails-test-suite-uber/src/test/groovy/grails/spring/BeanBuilderTests.groovy delete mode 100644 grails-test-suite-uber/src/test/groovy/grails/spring/DynamicElementReaderTests.groovy diff --git a/grails-core/src/main/groovy/grails/spring/WebBeanBuilder.java b/grails-core/src/main/groovy/grails/spring/WebBeanBuilder.java index 48c082526f1..a337f8af472 100644 --- a/grails-core/src/main/groovy/grails/spring/WebBeanBuilder.java +++ b/grails-core/src/main/groovy/grails/spring/WebBeanBuilder.java @@ -15,9 +15,9 @@ */ package grails.spring; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; -import org.codehaus.groovy.grails.commons.spring.WebRuntimeSpringConfiguration; import org.springframework.context.ApplicationContext; +import org.springframework.context.groovy.DefaultRuntimeSpringConfiguration; +import org.springframework.context.groovy.GroovyBeanDefinitionReader; /** * Extended version of the BeanBuilder class that provides support for constructing WebApplicationContext instances @@ -25,7 +25,7 @@ * @author Graeme Rocher * @since 1.0 */ -public class WebBeanBuilder extends BeanBuilder { +public class WebBeanBuilder extends GroovyBeanDefinitionReader { public WebBeanBuilder() { super(); @@ -44,7 +44,7 @@ public WebBeanBuilder(ApplicationContext parent, ClassLoader classLoader) { } @Override - protected RuntimeSpringConfiguration createRuntimeSpringConfiguration(ApplicationContext parent, ClassLoader classLoader) { - return new WebRuntimeSpringConfiguration(parent, classLoader); + protected org.springframework.context.groovy.RuntimeSpringConfiguration createRuntimeSpringConfiguration(ApplicationContext parent, ClassLoader classLoader) { + return new DefaultRuntimeSpringConfiguration(parent, classLoader); } } diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfigurator.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfigurator.java index 5a222b7b89b..d34ff731713 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfigurator.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfigurator.java @@ -15,7 +15,6 @@ */ package org.codehaus.groovy.grails.commons.spring; -import grails.spring.BeanBuilder; import grails.util.CollectionUtils; import grails.util.Environment; import grails.util.Holders; @@ -42,6 +41,9 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.groovy.DefaultRuntimeSpringConfiguration; +import org.springframework.context.groovy.GroovyBeanDefinitionReader; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; @@ -309,7 +311,7 @@ else if (LOG.isDebugEnabled()) { GrailsRuntimeConfigurator.loadSpringGroovyResources(springConfig, app); } - private static volatile BeanBuilder springGroovyResourcesBeanBuilder = null; + private static volatile GroovyBeanDefinitionReader springGroovyResourcesBeanBuilder = null; /** * Attempt to load the beans defined by a BeanBuilder DSL closure in "resources.groovy". @@ -356,8 +358,8 @@ public static void loadExternalSpringConfig(RuntimeSpringConfiguration config, f } } - public static BeanBuilder reloadSpringResourcesConfig(RuntimeSpringConfiguration config, GrailsApplication application, Class groovySpringResourcesClass) throws InstantiationException, IllegalAccessException { - springGroovyResourcesBeanBuilder = new BeanBuilder(null, config,Thread.currentThread().getContextClassLoader()); + public static GroovyBeanDefinitionReader reloadSpringResourcesConfig(RuntimeSpringConfiguration config, GrailsApplication application, Class groovySpringResourcesClass) throws InstantiationException, IllegalAccessException { + springGroovyResourcesBeanBuilder = new GroovyBeanDefinitionReader(null, config,Thread.currentThread().getContextClassLoader()); springGroovyResourcesBeanBuilder.setBinding(new Binding(CollectionUtils.newMap( "application", application, "grailsApplication", application))); // GRAILS-7550 diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsWebApplicationContext.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsWebApplicationContext.java index 147d47a1c5f..dd6324d5642 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsWebApplicationContext.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/GrailsWebApplicationContext.java @@ -15,7 +15,7 @@ */ package org.codehaus.groovy.grails.commons.spring; -import grails.spring.BeanBuilder; +import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @@ -26,6 +26,7 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; +import org.springframework.context.groovy.GroovyBeanDefinitionReader; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; @@ -157,10 +158,14 @@ protected ResourcePatternResolver getResourcePatternResolver() { protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { if (configLocations.length > 0) { for (String configLocation : configLocations) { - BeanBuilder beanBuilder = new BeanBuilder(getParent(),getClassLoader()); - final ServletContextResource resource = new ServletContextResource(getServletContext(), configLocation); - beanBuilder.loadBeans(resource); - beanBuilder.registerBeans(this); + try { + GroovyBeanDefinitionReader beanBuilder = new GroovyBeanDefinitionReader(getParent(),getClassLoader()); + final ServletContextResource resource = new ServletContextResource(getServletContext(), configLocation); + beanBuilder.loadBeans(resource); + beanBuilder.registerBeans(this); + } catch (IOException e) { + throw new RuntimeException(e); + } } } super.prepareBeanFactory(beanFactory); diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/WebRuntimeSpringConfiguration.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/WebRuntimeSpringConfiguration.java index 4ec96eb0295..7221e921e9b 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/WebRuntimeSpringConfiguration.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/spring/WebRuntimeSpringConfiguration.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; +import org.springframework.context.groovy.DefaultRuntimeSpringConfiguration; import org.springframework.context.support.GenericApplicationContext; import org.springframework.util.Assert; import org.springframework.web.context.ConfigurableWebApplicationContext; diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/AbstractGrailsPluginManager.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/AbstractGrailsPluginManager.java index c43c479368a..92933bb93da 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/AbstractGrailsPluginManager.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/AbstractGrailsPluginManager.java @@ -37,13 +37,13 @@ import org.codehaus.groovy.grails.commons.ArtefactHandler; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.cfg.ConfigurationHelper; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; import org.codehaus.groovy.grails.compiler.GrailsProjectWatcher; import org.codehaus.groovy.grails.io.support.GrailsResourceUtils; import org.codehaus.groovy.grails.plugins.exceptions.PluginException; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/CoreGrailsPlugin.groovy b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/CoreGrailsPlugin.groovy index cbccf640aa7..bb6d56bbceb 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/CoreGrailsPlugin.groovy +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/CoreGrailsPlugin.groovy @@ -24,9 +24,7 @@ import org.codehaus.groovy.grails.aop.framework.autoproxy.GroovyAwareAspectJAwar import org.codehaus.groovy.grails.aop.framework.autoproxy.GroovyAwareInfrastructureAdvisorAutoProxyCreator import org.codehaus.groovy.grails.commons.cfg.GrailsPlaceholderConfigurer import org.codehaus.groovy.grails.commons.cfg.MapBasedSmartPropertyOverrideConfigurer -import org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration import org.codehaus.groovy.grails.core.io.DefaultResourceLocator import org.codehaus.groovy.grails.plugins.support.aware.GrailsApplicationAwareBeanPostProcessor import org.codehaus.groovy.grails.plugins.support.aware.PluginManagerAwareBeanPostProcessor @@ -37,6 +35,8 @@ import org.springframework.beans.factory.config.CustomEditorConfigurer import org.springframework.beans.factory.config.MethodInvokingFactoryBean import org.springframework.beans.factory.support.DefaultListableBeanFactory import org.springframework.beans.factory.xml.XmlBeanDefinitionReader +import org.springframework.context.groovy.DefaultRuntimeSpringConfiguration +import org.springframework.context.groovy.RuntimeSpringConfiguration import org.springframework.core.io.Resource /** diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPlugin.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPlugin.java index 66b95b801e2..56d400ccbee 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPlugin.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPlugin.java @@ -15,7 +15,6 @@ */ package org.codehaus.groovy.grails.plugins; -import grails.spring.BeanBuilder; import grails.util.BuildScope; import grails.util.CollectionUtils; import grails.util.Environment; @@ -46,7 +45,6 @@ import org.codehaus.groovy.grails.commons.ArtefactHandler; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsClassUtils; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; import org.codehaus.groovy.grails.core.io.SpringResource; import org.codehaus.groovy.grails.exceptions.GrailsConfigurationException; import org.codehaus.groovy.grails.plugins.exceptions.PluginException; @@ -59,6 +57,8 @@ import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; +import org.springframework.context.groovy.GroovyBeanDefinitionReader; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; @@ -472,8 +472,8 @@ public ApplicationContext getParentCtx() { return application.getParentContext(); } - public BeanBuilder beans(Closure closure) { - BeanBuilder bb = new BeanBuilder(getParentCtx(), new GroovyClassLoader(application.getClassLoader())); + public GroovyBeanDefinitionReader beans(Closure closure) { + GroovyBeanDefinitionReader bb = new GroovyBeanDefinitionReader(getParentCtx(), new GroovyClassLoader(application.getClassLoader())); bb.invokeMethod("beans", new Object[]{closure}); return bb; } @@ -499,7 +499,7 @@ public void doWithRuntimeConfiguration(RuntimeSpringConfiguration springConfig) } Closure c = (Closure)plugin.getProperty(DO_WITH_SPRING); - BeanBuilder bb = new BeanBuilder(getParentCtx(),springConfig, application.getClassLoader()); + GroovyBeanDefinitionReader bb = new GroovyBeanDefinitionReader(getParentCtx(),springConfig, application.getClassLoader()); Binding b = new Binding(); b.setVariable("application", application); b.setVariable("manager", getManager()); diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPlugin.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPlugin.java index ca36f53c06f..79b78d8cf13 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPlugin.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPlugin.java @@ -24,10 +24,10 @@ import java.util.Map; import org.codehaus.groovy.grails.commons.GrailsApplication; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; import org.codehaus.groovy.grails.plugins.support.WatchPattern; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.core.io.Resource; import org.springframework.core.type.filter.TypeFilter; import org.w3c.dom.Element; diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPluginManager.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPluginManager.java index a7ab790cb7f..7ef24ba2e63 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPluginManager.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/GrailsPluginManager.java @@ -22,10 +22,10 @@ import java.util.Map; import org.codehaus.groovy.grails.commons.GrailsApplication; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; import org.codehaus.groovy.grails.plugins.exceptions.PluginException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.core.io.Resource; import org.springframework.core.type.filter.TypeFilter; import org.springframework.web.context.ServletContextAware; diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/ProfilingGrailsPluginManager.java b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/ProfilingGrailsPluginManager.java index 9a47b207306..33abaf530ca 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/ProfilingGrailsPluginManager.java +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/plugins/ProfilingGrailsPluginManager.java @@ -18,10 +18,11 @@ import grails.build.logging.GrailsConsole; import groovy.lang.GroovySystem; import groovy.lang.MetaClassRegistry; + import org.codehaus.groovy.grails.commons.GrailsApplication; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; import org.codehaus.groovy.grails.plugins.exceptions.PluginException; import org.springframework.context.ApplicationContext; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.core.io.Resource; /** diff --git a/grails-core/src/main/groovy/org/codehaus/groovy/grails/project/loader/GrailsProjectLoader.groovy b/grails-core/src/main/groovy/org/codehaus/groovy/grails/project/loader/GrailsProjectLoader.groovy index a9dc1d279df..af613d102d5 100644 --- a/grails-core/src/main/groovy/org/codehaus/groovy/grails/project/loader/GrailsProjectLoader.groovy +++ b/grails-core/src/main/groovy/org/codehaus/groovy/grails/project/loader/GrailsProjectLoader.groovy @@ -15,13 +15,15 @@ */ package org.codehaus.groovy.grails.project.loader -import grails.spring.BeanBuilder import grails.spring.WebBeanBuilder import grails.util.BuildSettings import grails.util.Holders import grails.util.PluginBuildSettings import groovy.transform.CompileStatic import groovy.transform.TypeCheckingMode + +import javax.servlet.ServletContext + import org.codehaus.groovy.grails.cli.api.BaseSettingsApi import org.codehaus.groovy.grails.cli.jndi.JndiBindingSupport import org.codehaus.groovy.grails.cli.support.GrailsBuildEventListener @@ -39,11 +41,10 @@ import org.codehaus.groovy.grails.project.plugins.GrailsProjectPluginLoader import org.codehaus.groovy.grails.support.CommandLineResourceLoader import org.springframework.beans.factory.config.MethodInvokingFactoryBean import org.springframework.context.ApplicationContext +import org.springframework.context.groovy.GroovyBeanDefinitionReader import org.springframework.mock.web.MockServletContext import org.springframework.web.context.WebApplicationContext -import javax.servlet.ServletContext - /** * Capable of bootstrapping a Grails project and returning the loaded ApplicationContext * @@ -81,7 +82,7 @@ class GrailsProjectLoader extends BaseSettingsApi{ @CompileStatic GrailsApplication loadApplication() { buildEventListener.triggerEvent("AppLoadStart", ["Loading Grails Application"]) - BeanBuilder beanDefinitions + GroovyBeanDefinitionReader beanDefinitions profile("Loading parent ApplicationContext") { def builder = parentContext ? new WebBeanBuilder(parentContext) : new WebBeanBuilder() beanDefinitions = defineParentBeans(builder) @@ -164,7 +165,7 @@ class GrailsProjectLoader extends BaseSettingsApi{ } @CompileStatic(TypeCheckingMode.SKIP) - protected BeanBuilder defineParentBeans(WebBeanBuilder builder) { + protected GroovyBeanDefinitionReader defineParentBeans(WebBeanBuilder builder) { builder.beans { grailsApplication(DefaultGrailsApplication, pluginSettings.getArtefactResourcesForCurrentEnvironment()) } diff --git a/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceHolderConfigurerCorePluginRuntimeSpec.groovy b/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceHolderConfigurerCorePluginRuntimeSpec.groovy index 2cc730e3ee0..abd39e2c127 100644 --- a/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceHolderConfigurerCorePluginRuntimeSpec.groovy +++ b/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceHolderConfigurerCorePluginRuntimeSpec.groovy @@ -1,8 +1,9 @@ package org.codehaus.groovy.grails.commons.cfg -import grails.spring.BeanBuilder import org.codehaus.groovy.grails.commons.DefaultGrailsApplication import org.codehaus.groovy.grails.plugins.CoreGrailsPlugin +import org.springframework.context.groovy.GroovyBeanDefinitionReader + import spock.lang.Issue import spock.lang.Specification @@ -14,11 +15,11 @@ class GrailsPlaceHolderConfigurerCorePluginRuntimeSpec extends Specification{ @Issue('GRAILS-10130') void "Test that system properties are used to replace values at runtime with GrailsPlaceHolderConfigurer"() { given:"A configured application context" - def parent = new BeanBuilder() + def parent = new GroovyBeanDefinitionReader() parent.beans { grailsApplication(DefaultGrailsApplication) } - def bb = new BeanBuilder(parent.createApplicationContext()) + def bb = new GroovyBeanDefinitionReader(parent.createApplicationContext()) final beanBinding = new Binding() beanBinding.setVariable('application', new DefaultGrailsApplication()) diff --git a/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceholderConfigurerSpec.groovy b/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceholderConfigurerSpec.groovy index d0bc9578603..18a944cf715 100644 --- a/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceholderConfigurerSpec.groovy +++ b/grails-core/src/test/groovy/org/codehaus/groovy/grails/commons/cfg/GrailsPlaceholderConfigurerSpec.groovy @@ -1,7 +1,8 @@ package org.codehaus.groovy.grails.commons.cfg -import grails.spring.BeanBuilder import org.codehaus.groovy.grails.commons.DefaultGrailsApplication +import org.springframework.context.groovy.GroovyBeanDefinitionReader + import spock.lang.Issue import spock.lang.Specification @@ -14,7 +15,7 @@ class GrailsPlaceholderConfigurerSpec extends Specification { when:"A bean is defined with a placeholder" def application = new DefaultGrailsApplication() application.config.foo.bar="test" - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() bb.beans { addBeanFactoryPostProcessor(new GrailsPlaceholderConfigurer(application)) testBean(TestBean) { @@ -34,7 +35,7 @@ class GrailsPlaceholderConfigurerSpec extends Specification { def application = new DefaultGrailsApplication() application.config.bar.foo="test" application.config.more.stuff='another ${place.holder}' - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() bb.beans { addBeanFactoryPostProcessor(new GrailsPlaceholderConfigurer(application)) testBean(TestBean) { @@ -54,7 +55,7 @@ class GrailsPlaceholderConfigurerSpec extends Specification { application.config.foo.bar="test" application.config.grails.spring.placeholder.prefix='£{' application.setConfig(application.config) - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() bb.beans { addBeanFactoryPostProcessor(new GrailsPlaceholderConfigurer(application)) testBean(TestBean) { diff --git a/grails-plugin-testing/src/main/groovy/grails/test/mixin/support/GrailsUnitTestMixin.groovy b/grails-plugin-testing/src/main/groovy/grails/test/mixin/support/GrailsUnitTestMixin.groovy index 1186f2766bf..146384ae087 100644 --- a/grails-plugin-testing/src/main/groovy/grails/test/mixin/support/GrailsUnitTestMixin.groovy +++ b/grails-plugin-testing/src/main/groovy/grails/test/mixin/support/GrailsUnitTestMixin.groovy @@ -16,7 +16,6 @@ package grails.test.mixin.support import grails.async.Promises -import grails.spring.BeanBuilder import grails.test.GrailsMock import grails.test.MockUtils import grails.util.Holders @@ -50,6 +49,7 @@ import org.junit.BeforeClass import org.springframework.beans.CachedIntrospectionResults import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor import org.springframework.context.MessageSource +import org.springframework.context.groovy.GroovyBeanDefinitionReader import org.springframework.context.support.ConversionServiceFactoryBean import org.springframework.context.support.StaticMessageSource import org.springframework.mock.web.MockServletContext @@ -80,7 +80,7 @@ class GrailsUnitTestMixin { @CompileStatic static void defineBeans(Closure callable) { - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() def binding = new Binding() binding.setVariable "application", grailsApplication bb.setBinding binding diff --git a/grails-spring/src/main/groovy/grails/spring/BeanBuilder.java b/grails-spring/src/main/groovy/grails/spring/BeanBuilder.java deleted file mode 100644 index defe47209bb..00000000000 --- a/grails-spring/src/main/groovy/grails/spring/BeanBuilder.java +++ /dev/null @@ -1,975 +0,0 @@ -/* - * Copyright 2004-2005 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 grails.spring; - -import groovy.lang.Binding; -import groovy.lang.Closure; -import groovy.lang.GString; -import groovy.lang.GroovyObject; -import groovy.lang.GroovyObjectSupport; -import groovy.lang.GroovyShell; -import groovy.lang.MetaClass; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codehaus.groovy.grails.commons.spring.BeanConfiguration; -import org.codehaus.groovy.grails.commons.spring.DefaultBeanConfiguration; -import org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; -import org.codehaus.groovy.runtime.DefaultGroovyMethods; -import org.codehaus.groovy.runtime.InvokerHelper; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; -import org.springframework.beans.factory.parsing.EmptyReaderEventListener; -import org.springframework.beans.factory.parsing.FailFastProblemReporter; -import org.springframework.beans.factory.parsing.Location; -import org.springframework.beans.factory.parsing.NullSourceExtractor; -import org.springframework.beans.factory.parsing.Problem; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.ManagedList; -import org.springframework.beans.factory.support.ManagedMap; -import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; -import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; -import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver; -import org.springframework.beans.factory.xml.NamespaceHandler; -import org.springframework.beans.factory.xml.NamespaceHandlerResolver; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.beans.factory.xml.XmlReaderContext; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.util.Assert; - -/** - *

Runtime bean configuration wrapper. Like a Groovy builder, but more of a DSL for - * Spring configuration. Allows syntax like:

- * - *
- * import org.hibernate.SessionFactory
- * import org.apache.tomcat.jdbc.pool.DataSource
- *
- * BeanBuilder builder = new BeanBuilder()
- * builder.beans {
- *   dataSource(DataSource) {                  // <--- invokeMethod
- *      driverClassName = "org.h2.Driver"
- *      url = "jdbc:h2:mem:grailsDB"
- *      username = "sa"                            // <-- setProperty
- *      password = ""
- *      settings = [mynew:"setting"]
- *  }
- *  sessionFactory(SessionFactory) {
- *         dataSource = dataSource                 // <-- getProperty for retrieving refs
- *  }
- *  myService(MyService) {
- *      nestedBean = { AnotherBean bean->          // <-- setProperty with closure for nested bean
- *              dataSource = dataSource
- *      }
- *  }
- * }
- * 
- *

- * You can also use the Spring IO API to load resources containing beans defined as a Groovy - * script using either the constructors or the loadBeans(Resource[] resources) method - *

- * - * @author Graeme Rocher - * @since 0.4 - * - */ -public class BeanBuilder extends GroovyObjectSupport { - private static final Log LOG = LogFactory.getLog(BeanBuilder.class); - private static final String CREATE_APPCTX = "createApplicationContext"; - private static final String REGISTER_BEANS = "registerBeans"; - private static final String BEANS = "beans"; - private static final String REF = "ref"; - private RuntimeSpringConfiguration springConfig; - private BeanConfiguration currentBeanConfig; - private Map deferredProperties = new HashMap(); - private ApplicationContext parentCtx; - private Map binding = Collections.emptyMap(); - private ClassLoader classLoader = null; - private NamespaceHandlerResolver namespaceHandlerResolver; - private Map namespaceHandlers = new HashMap(); - private XmlBeanDefinitionReader xmlBeanDefinitionReader; - private Map namespaces = new HashMap(); - private Resource beanBuildResource = new ByteArrayResource(new byte[0]); - private XmlReaderContext readerContext; - private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); - - public BeanBuilder() { - this(null,null); - } - - public BeanBuilder(ClassLoader classLoader) { - this(null, classLoader); - } - - public BeanBuilder(ApplicationContext parent) { - this(parent, null); - } - - public BeanBuilder(ApplicationContext parent,ClassLoader classLoader) { - this(parent, null, classLoader); - } - - public BeanBuilder(ApplicationContext parentCtx, RuntimeSpringConfiguration springConfig, ClassLoader classLoader) { - this.springConfig = springConfig == null ? createRuntimeSpringConfiguration(parentCtx, classLoader) : springConfig; - this.parentCtx = parentCtx; - this.classLoader = classLoader; - initializeSpringConfig(); - } - - public void setResourcePatternResolver(ResourcePatternResolver resourcePatternResolver) { - Assert.notNull(resourcePatternResolver, "The argument [resourcePatternResolver] cannot be null"); - this.resourcePatternResolver = resourcePatternResolver; - } - - protected void initializeSpringConfig() { - xmlBeanDefinitionReader = new XmlBeanDefinitionReader((GenericApplicationContext)springConfig.getUnrefreshedApplicationContext()); - initializeBeanBuilderForClassLoader(classLoader); - } - - public void setClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader == null ? getClass().getClassLoader() : classLoader; - initializeBeanBuilderForClassLoader(classLoader); - } - - protected void initializeBeanBuilderForClassLoader(ClassLoader classLoader) { - xmlBeanDefinitionReader.setBeanClassLoader(classLoader); - namespaceHandlerResolver = new DefaultNamespaceHandlerResolver(this.classLoader); - readerContext = new XmlReaderContext(beanBuildResource, new FailFastProblemReporter(), new EmptyReaderEventListener(), - new NullSourceExtractor(), xmlBeanDefinitionReader, namespaceHandlerResolver); - } - - public void setNamespaceHandlerResolver(NamespaceHandlerResolver namespaceHandlerResolver) { - this.namespaceHandlerResolver = namespaceHandlerResolver; - } - - protected RuntimeSpringConfiguration createRuntimeSpringConfiguration(ApplicationContext parent, ClassLoader cl) { - return new DefaultRuntimeSpringConfiguration(parent, cl); - } - - public Log getLog() { - return LOG; - } - - /** - * Imports Spring bean definitions from either XML or Groovy sources into the current bean builder instance - * - * @param resourcePattern The resource pattern - */ - public void importBeans(String resourcePattern) { - try { - Resource[] resources = resourcePatternResolver.getResources(resourcePattern); - for (Resource resource : resources) { - if (resource.getFilename().endsWith(".groovy")) { - loadBeans(resource); - } - else if (resource.getFilename().endsWith(".xml")) { - SimpleBeanDefinitionRegistry beanRegistry = new SimpleBeanDefinitionRegistry(); - XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(beanRegistry); - beanReader.loadBeanDefinitions(resource); - String[] beanNames = beanRegistry.getBeanDefinitionNames(); - for (String beanName : beanNames) { - springConfig.addBeanDefinition(beanName, beanRegistry.getBeanDefinition(beanName)); - } - } - } - } catch (IOException e) { - LOG.error("Error loading beans for resource pattern: " + resourcePattern, e); - } - } - - /** - * Defines a Spring namespace definition to use. - * - * @param definition The definition - */ - public void xmlns(Map definition) { - Assert.notNull(namespaceHandlerResolver, "You cannot define a Spring namespace without a [namespaceHandlerResolver] set"); - if (definition.isEmpty()) { - return; - } - - for (Map.Entry entry : definition.entrySet()) { - String namespace = entry.getKey(); - String uri = entry.getValue() == null ? null : entry.getValue(); - - Assert.notNull(uri, "Namespace definition cannot supply a null URI"); - - final NamespaceHandler namespaceHandler = namespaceHandlerResolver.resolve(uri); - if (namespaceHandler == null) { - throw new BeanDefinitionParsingException( - new Problem("No namespace handler found for URI: " + uri, - new Location(readerContext.getResource()))); - } - namespaceHandlers.put(namespace, namespaceHandler); - namespaces.put(namespace, uri); - } - } - - /** - * Retrieves the parent ApplicationContext - * @return The parent ApplicationContext - */ - public ApplicationContext getParentCtx() { - return parentCtx; - } - - /** - * Retrieves the RuntimeSpringConfiguration instance used the the BeanBuilder - * @return The RuntimeSpringConfiguration instance - */ - public RuntimeSpringConfiguration getSpringConfig() { - return springConfig; - } - - /** - * Retrieves a BeanDefinition for the given name - * @param name The bean definition - * @return The BeanDefinition instance - */ - public BeanDefinition getBeanDefinition(String name) { - if (!getSpringConfig().containsBean(name)) { - return null; - } - return getSpringConfig().getBeanConfig(name).getBeanDefinition(); - } - - /** - * Retrieves all BeanDefinitions for this BeanBuilder - * - * @return A map of BeanDefinition instances with the bean id as the key - */ - public Map getBeanDefinitions() { - Map beanDefinitions = new HashMap(); - for (String beanName : getSpringConfig().getBeanNames()) { - beanDefinitions.put(beanName, getSpringConfig().getBeanConfig(beanName).getBeanDefinition()); - } - return beanDefinitions; - } - - /** - * Sets the runtime Spring configuration instance to use. This is not necessary to set - * and is configured to default value if not, but is useful for integrating with other - * spring configuration mechanisms @see org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator - * - * @param springConfig The spring config - */ - public void setSpringConfig(RuntimeSpringConfiguration springConfig) { - this.springConfig = springConfig; - initializeSpringConfig(); - } - - /** - * Defers the adding of a property to a bean definition until later. - * This is for a case where you assign a property to a list that may not contain bean references at - * that point of asignment, but may later hence it would need to be managed - * - * @author Graeme Rocher - */ - private class DeferredProperty { - private BeanConfiguration config; - private String name; - private Object value; - - DeferredProperty(BeanConfiguration config, String name, Object value) { - this.config = config; - this.name = name; - this.value = value; - } - - public void setInBeanConfig() { - config.addProperty(name, value); - } - } - - /** - * Adds new properties to runtime references. - * - * @author Graeme Rocher - * @since 0.4 - */ - private class ConfigurableRuntimeBeanReference extends RuntimeBeanReference implements GroovyObject { - - private MetaClass metaClass; - private BeanConfiguration beanConfig; - - public ConfigurableRuntimeBeanReference(String beanName, BeanConfiguration beanConfig, boolean toParent) { - super(beanName, toParent); - Assert.notNull(beanConfig, "Argument [beanConfig] cannot be null"); - this.beanConfig = beanConfig; - metaClass = InvokerHelper.getMetaClass(this); - } - - public MetaClass getMetaClass() { - return metaClass; - } - - public Object getProperty(String property) { - if (property.equals("beanName")) { - return getBeanName(); - } - if (property.equals("source")) { - return getSource(); - } - if (beanConfig != null) { - return new WrappedPropertyValue(property, beanConfig.getPropertyValue(property)); - } - return metaClass.getProperty(this, property); - } - - /** - * Wraps a BeanConfiguration property an ensures that any RuntimeReference additions to it are - * deferred for resolution later. - */ - private class WrappedPropertyValue extends GroovyObjectSupport { - private Object propertyValue; - private String propertyName; - public WrappedPropertyValue(String propertyName, Object propertyValue) { - this.propertyValue = propertyValue; - this.propertyName = propertyName; - } - - @SuppressWarnings("unused") - public void leftShift(Object value) { - InvokerHelper.invokeMethod(propertyValue, "leftShift", value); - updateDeferredProperties(value); - } - - @SuppressWarnings("unused") - public boolean add(Object value) { - boolean retval = (Boolean) InvokerHelper.invokeMethod(propertyValue, "add", value); - updateDeferredProperties(value); - return retval; - } - - @SuppressWarnings("unused") - public boolean addAll(@SuppressWarnings("rawtypes") Collection values) { - boolean retval = (Boolean) InvokerHelper.invokeMethod(propertyValue, "addAll", values); - for (Object value : values) { - updateDeferredProperties(value); - } - return retval; - } - - @Override - public Object invokeMethod(String name, Object args) { - return InvokerHelper.invokeMethod(propertyValue, name, args); - } - - @Override - public Object getProperty(String name) { - return InvokerHelper.getProperty(propertyValue, name); - } - - @Override - public void setProperty(String name, Object value) { - InvokerHelper.setProperty(propertyValue, name, value); - } - - private void updateDeferredProperties(Object value) { - if (value instanceof RuntimeBeanReference) { - deferredProperties.put(beanConfig.getName(), new DeferredProperty(beanConfig, propertyName, propertyValue)); - } - } - } - - public Object invokeMethod(String name, Object args) { - return metaClass.invokeMethod(this, name, args); - } - - public void setMetaClass(MetaClass metaClass) { - this.metaClass = metaClass; - } - - public void setProperty(String property, Object newValue) { - if (!addToDeferred(beanConfig,property, newValue)) { - beanConfig.setPropertyValue(property, newValue); - } - } - } - - /** - * Takes a resource pattern as (@see org.springframework.core.io.support.PathMatchingResourcePatternResolver) - * This allows you load multiple bean resources in this single builder - * - * eg loadBeans("classpath:*Beans.groovy") - * - * @param resourcePattern The resource pattern - * @throws IOException When the path cannot be matched - */ - public void loadBeans(String resourcePattern) throws IOException { - loadBeans(new PathMatchingResourcePatternResolver().getResources(resourcePattern)); - } - - /** - * Loads a single Resource into the bean builder - * - * @param resource The resource to load - */ - public void loadBeans(Resource resource) { - beanBuildResource = resource; - loadBeans(new Resource[]{resource}); - } - - /** - * Loads a set of given beans - * @param resources The resources to load - * @throws IOException Thrown if there is an error reading one of the passes resources - */ - public void loadBeans(Resource[] resources) { - @SuppressWarnings("rawtypes") Closure beans = new Closure(this) { - private static final long serialVersionUID = -2778328821635253740L; - - @Override - public Object call(Object... args) { - invokeBeanDefiningClosure((Closure)args[0]); - return null; - } - }; - - Binding b = new Binding() { - @Override - public void setVariable(String name, Object value) { - if (currentBeanConfig == null) { - super.setVariable(name, value); - } - else { - setPropertyOnBeanConfig(name, value); - } - } - }; - b.setVariable("beans", beans); - - for (Resource resource : resources) { - try { - GroovyShell shell = classLoader == null ? new GroovyShell(b) : new GroovyShell(classLoader, b); - shell.evaluate(new InputStreamReader(resource.getInputStream())); - } - catch (Throwable e) { - throw new BeanDefinitionParsingException( - new Problem("Error evaluating bean definition script: " + e.getMessage(), new Location(resource), null, e)); - } - } - } - - /** - * Register a set of beans with the given bean registry. Most - * application contexts are bean registries. - */ - public void registerBeans(BeanDefinitionRegistry registry) { - finalizeDeferredProperties(); - - if (registry instanceof GenericApplicationContext) { - GenericApplicationContext ctx = (GenericApplicationContext) registry; - ctx.setClassLoader(classLoader); - ctx.getBeanFactory().setBeanClassLoader(classLoader); - } - - springConfig.registerBeansWithRegistry(registry); - } - - /** - * Registers bean definitions with another instance of RuntimeSpringConfiguration, overriding any beans in the target. - * - * @param targetSpringConfig The RuntimeSpringConfiguration object - */ - public void registerBeans(RuntimeSpringConfiguration targetSpringConfig) { - springConfig.registerBeansWithConfig(targetSpringConfig); - } - - /** - * Overrides method invocation to create beans for each method name that takes a class argument. - */ - @Override - public Object invokeMethod(String name, Object arg) { - Object[] args = (Object[])arg; - - if (CREATE_APPCTX.equals(name)) { - return createApplicationContext(); - } - - if (REGISTER_BEANS.equals(name) && args.length == 1 && args[0] instanceof GenericApplicationContext) { - registerBeans((GenericApplicationContext)args[0]); - return null; - } - - if (BEANS.equals(name) && args.length == 1 && args[0] instanceof Closure) { - return beans((Closure)args[0]); - } - - if (REF.equals(name)) { - String refName; - Assert.notNull(args[0], "Argument to ref() is not a valid bean or was not found"); - - if (args[0] instanceof RuntimeBeanReference) { - refName = ((RuntimeBeanReference)args[0]).getBeanName(); - } - else { - refName = args[0].toString(); - } - - boolean parentRef = false; - if (args.length > 1) { - if (args[1] instanceof Boolean) { - parentRef = (Boolean) args[1]; - } - } - return new RuntimeBeanReference(refName, parentRef); - } - - if (namespaceHandlers.containsKey(name) && args.length > 0 && (args[0] instanceof Closure)) { - createDynamicElementReader(name, true).invokeMethod("doCall", args); - return this; - } - - if (args.length > 0 && args[0] instanceof Closure) { - // abstract bean definition - return invokeBeanDefiningMethod(name, args); - } - - if (args.length > 0 && args[0] instanceof Class || args.length > 0 && args[0] instanceof RuntimeBeanReference || args.length > 0 && args[0] instanceof Map) { - return invokeBeanDefiningMethod(name, args); - } - - if (args.length > 1 && args[args.length - 1] instanceof Closure) { - return invokeBeanDefiningMethod(name, args); - } - - ApplicationContext ctx = springConfig.getUnrefreshedApplicationContext(); - MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx); - if (!mc.respondsTo(ctx, name, args).isEmpty()) { - return mc.invokeMethod(ctx,name, args); - } - - return this; - } - - /** - * Defines a set of beans for the given block or closure. - * - * @param c The block or closure - * @return This BeanBuilder instance - */ - public BeanBuilder beans(Closure c) { - return invokeBeanDefiningClosure(c); - } - - /** - * Creates an ApplicationContext from the current state of the BeanBuilder - * @return The ApplicationContext instance - */ - public ApplicationContext createApplicationContext() { - finalizeDeferredProperties(); - return springConfig.getApplicationContext(); - } - - protected void finalizeDeferredProperties() { - for (DeferredProperty dp : deferredProperties.values()) { - if (dp.value instanceof List) { - dp.value = manageListIfNecessary(dp.value); - } - else if (dp.value instanceof Map) { - dp.value = manageMapIfNecessary(dp.value); - } - dp.setInBeanConfig(); - } - deferredProperties.clear(); - } - - protected boolean addToDeferred(BeanConfiguration beanConfig, String property, Object newValue) { - if (newValue instanceof List) { - deferredProperties.put(currentBeanConfig.getName() + property, - new DeferredProperty(currentBeanConfig, property, newValue)); - return true; - } - - if (newValue instanceof Map) { - deferredProperties.put(currentBeanConfig.getName() + property, - new DeferredProperty(currentBeanConfig, property, newValue)); - return true; - } - - return false; - } - - /** - * Called when a bean definition node is called. - * - * @param name The name of the bean to define - * @param args The arguments to the bean. The first argument is the class name, the last argument is sometimes a closure. All - * the arguments in between are constructor arguments - * @return The bean configuration instance - */ - protected BeanConfiguration invokeBeanDefiningMethod(String name, Object[] args) { - - boolean hasClosureArgument = args[args.length - 1] instanceof Closure; - if (args[0] instanceof Class) { - Class beanClass = args[0] instanceof Class ? (Class)args[0] : args[0].getClass(); - - if (args.length >= 1) { - if (hasClosureArgument) { - if (args.length - 1 != 1) { - currentBeanConfig = springConfig.addSingletonBean(name, beanClass, resolveConstructorArguments(args, 1, args.length - 1)); - } - else { - currentBeanConfig = springConfig.addSingletonBean(name, beanClass); - } - } - else { - currentBeanConfig = springConfig.addSingletonBean(name, beanClass, resolveConstructorArguments(args, 1, args.length)); - } - } - } - else if (args[0] instanceof RuntimeBeanReference) { - currentBeanConfig = springConfig.addSingletonBean(name); - currentBeanConfig.setFactoryBean(((RuntimeBeanReference)args[0]).getBeanName()); - } - else if (args[0] instanceof Map) { - // named constructor arguments - if (args.length > 1 && args[1] instanceof Class) { - List constructorArgs = resolveConstructorArguments(args, 2, hasClosureArgument ? args.length - 1 : args.length); - currentBeanConfig = springConfig.addSingletonBean(name, (Class)args[1], constructorArgs); - - @SuppressWarnings("rawtypes") - Map namedArgs = (Map)args[0]; - for (Object o : namedArgs.keySet()) { - String propName = (String) o; - setProperty(propName, namedArgs.get(propName)); - } - } - // factory method syntax - else { - currentBeanConfig = springConfig.addSingletonBean(name); - - //First arg is the map containing factoryBean : factoryMethod - @SuppressWarnings("rawtypes") - Map.Entry factoryBeanEntry = (Map.Entry)((Map)args[0]).entrySet().iterator().next(); - // If we have a closure body, that will be the last argument. - // In between are the constructor args - int constructorArgsTest = hasClosureArgument?2:1; - // If we have more than this number of args, we have constructor args - if (args.length > constructorArgsTest) { - //factory-method requires args - int endOfConstructArgs = hasClosureArgument ? args.length - 1 : args.length; - currentBeanConfig = springConfig.addSingletonBean(name, null, resolveConstructorArguments(args, 1, endOfConstructArgs)); - } else { - currentBeanConfig = springConfig.addSingletonBean(name); - } - currentBeanConfig.setFactoryBean(factoryBeanEntry.getKey().toString()); - currentBeanConfig.setFactoryMethod(factoryBeanEntry.getValue().toString()); - } - } - else if (args[0] instanceof Closure) { - currentBeanConfig = springConfig.addAbstractBean(name); - } - else { - List constructorArgs = resolveConstructorArguments(args, 0, hasClosureArgument ? args.length - 1 : args.length); - currentBeanConfig = new DefaultBeanConfiguration(name, null, constructorArgs); - springConfig.addBeanConfiguration(name,currentBeanConfig); - } - - if (hasClosureArgument) { - Closure callable = (Closure)args[args.length - 1]; - callable.setDelegate(this); - callable.setResolveStrategy(Closure.DELEGATE_FIRST); - callable.call(new Object[]{currentBeanConfig}); - } - - BeanConfiguration beanConfig = currentBeanConfig; - currentBeanConfig = null; - return beanConfig; - } - - @SuppressWarnings("rawtypes") - protected List resolveConstructorArguments(Object[] args, int start, int end) { - Object[] constructorArgs = subarray(args, start, end); - filterGStringReferences(constructorArgs); - for (int i = 0; i < constructorArgs.length; i++) { - if (constructorArgs[i] instanceof List) { - constructorArgs[i] = manageListIfNecessary(constructorArgs[i]); - } else if (constructorArgs[i] instanceof Map) { - constructorArgs[i] = manageMapIfNecessary(constructorArgs[i]); - } - } - return Arrays.asList(constructorArgs); - } - - protected Object[] subarray(Object[] args, int i, int j) { - Assert.isTrue(j <= args.length, "Upper bound can't be greater than array length"); - Object[] b = new Object[j - i]; - int n = 0; - for (int k = i; k < j; k++,n++) { - b[n] = args[k]; - } - return b; - } - - protected void filterGStringReferences(Object[] constructorArgs) { - for (int i = 0; i < constructorArgs.length; i++) { - Object constructorArg = constructorArgs[i]; - if (constructorArg instanceof GString) { - constructorArgs[i] = constructorArg.toString(); - } - } - } - - /** - * When an method's argument is only a closure it is a set of bean definitions. - * - * @param callable The closure argument - * @return This BeanBuilder instance - */ - protected BeanBuilder invokeBeanDefiningClosure(Closure callable) { - - callable.setDelegate(this); -// callable.setResolveStrategy(Closure.DELEGATE_FIRST); - callable.call(); - finalizeDeferredProperties(); - - return this; - } - - /** - * Overrides property setting in the scope of the BeanBuilder to set - * properties on the current BeanConfiguration. - */ - @Override - public void setProperty(String name, Object value) { - if (currentBeanConfig != null) { - setPropertyOnBeanConfig(name, value); - } - } - - /** - * Defines an inner bean definition. - * - * @param type The bean type - * @return The bean definition - */ - public AbstractBeanDefinition bean(Class type) { - return springConfig.createSingletonBean(type).getBeanDefinition(); - } - - /** - * Defines an inner bean definition. - * - * @param type The bean type - * @param args The constructors arguments and closure configurer - * @return The bean definition - */ - @SuppressWarnings("rawtypes") - public AbstractBeanDefinition bean(Class type, Object...args) { - BeanConfiguration current = currentBeanConfig; - try { - Closure callable = null; - Collection constructorArgs = null; - if (args != null && args.length > 0) { - int index = args.length; - Object lastArg = args[index-1]; - - if (lastArg instanceof Closure) { - callable = (Closure) lastArg; - index--; - } - if (index > -1) { - constructorArgs = resolveConstructorArguments(args, 0, index); - } - } - currentBeanConfig = constructorArgs == null ? springConfig.createSingletonBean(type) : springConfig.createSingletonBean(type, constructorArgs); - if (callable != null) { - callable.call(new Object[]{currentBeanConfig}); - } - return currentBeanConfig.getBeanDefinition(); - - } - finally { - currentBeanConfig = current; - } - } - - protected void setPropertyOnBeanConfig(String name, Object value) { - if (value instanceof GString) { - value = value.toString(); - } - if (addToDeferred(currentBeanConfig, name, value)) { - return; - } - - if (value instanceof Closure) { - BeanConfiguration current = currentBeanConfig; - try { - Closure callable = (Closure)value; - - Class parameterType = callable.getParameterTypes()[0]; - if (parameterType.equals(Object.class)) { - currentBeanConfig = springConfig.createSingletonBean(""); - callable.call(new Object[]{currentBeanConfig}); - } - else { - currentBeanConfig = springConfig.createSingletonBean(parameterType); - callable.call(); - } - - value = currentBeanConfig.getBeanDefinition(); - } - finally { - currentBeanConfig = current; - } - } - currentBeanConfig.addProperty(name, value); - } - - /** - * Checks whether there are any runtime refs inside a Map and converts - * it to a ManagedMap if necessary. - * - * @param value The current map - * @return A ManagedMap or a normal map - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected Object manageMapIfNecessary(Object value) { - Map map = (Map)value; - boolean containsRuntimeRefs = false; - for (Object e : map.values()) { - if (e instanceof RuntimeBeanReference) { - containsRuntimeRefs = true; - break; - } - } - if (containsRuntimeRefs) { - Map managedMap = new ManagedMap(); - managedMap.putAll(map); - return managedMap; - } - return value; - } - - /** - * Checks whether there are any runtime refs inside the list and - * converts it to a ManagedList if necessary. - * - * @param value The object that represents the list - * @return Either a new list or a managed one - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected Object manageListIfNecessary(Object value) { - List list = (List)value; - boolean containsRuntimeRefs = false; - for (Object e : list) { - if (e instanceof RuntimeBeanReference) { - containsRuntimeRefs = true; - break; - } - } - if (containsRuntimeRefs) { - List tmp = new ManagedList(); - tmp.addAll((List)value); - value = tmp; - } - return value; - } - - /** - * Overrides property retrieval in the scope of the BeanBuilder to either: - * - * a) Retrieve a variable from the bean builder's binding if it exists - * b) Retrieve a RuntimeBeanReference for a specific bean if it exists - * c) Otherwise just delegate to super.getProperty which will resolve properties from the BeanBuilder itself - */ - @Override - public Object getProperty(String name) { - - if (binding.containsKey(name)) { - return binding.get(name); - } - - if (namespaceHandlers.containsKey(name)) { - return createDynamicElementReader(name, currentBeanConfig != null); - } - - if (springConfig.containsBean(name)) { - BeanConfiguration beanConfig = springConfig.getBeanConfig(name); - if (beanConfig != null) { - return new ConfigurableRuntimeBeanReference(name, springConfig.getBeanConfig(name) ,false); - } - return new RuntimeBeanReference(name,false); - } - - // this is to deal with the case where the property setter is the last - // statement in a closure (hence the return value) - if (currentBeanConfig != null) { - if (currentBeanConfig.hasProperty(name)) { - return currentBeanConfig.getPropertyValue(name); - } - DeferredProperty dp = deferredProperties.get(currentBeanConfig.getName()+name); - if (dp != null) { - return dp.value; - } - return super.getProperty(name); - } - - return super.getProperty(name); - } - - protected DynamicElementReader createDynamicElementReader(String namespace, final boolean decorator) { - NamespaceHandler handler = namespaceHandlers.get(namespace); - ParserContext parserContext = new ParserContext(readerContext, new BeanDefinitionParserDelegate(readerContext)); - final DynamicElementReader dynamicElementReader = new DynamicElementReader(namespace, namespaces, handler, parserContext) { - @Override - protected void afterInvocation() { - if (!decorator) { - currentBeanConfig = null; - } - } - }; - dynamicElementReader.setClassLoader(classLoader); - if (currentBeanConfig != null) { - dynamicElementReader.setBeanConfiguration(currentBeanConfig); - } - else if (!decorator) { - currentBeanConfig = new DefaultBeanConfiguration(namespace); - dynamicElementReader.setBeanConfiguration(currentBeanConfig); - } - dynamicElementReader.setBeanDecorator(decorator); - return dynamicElementReader; - } - - /** - * Sets the binding (the variables available in the scope of the BeanBuilder). - * @param b The Binding instance - */ - @SuppressWarnings("unchecked") - public void setBinding(Binding b) { - binding = b.getVariables(); - } -} diff --git a/grails-spring/src/main/groovy/grails/spring/DynamicElementReader.groovy b/grails-spring/src/main/groovy/grails/spring/DynamicElementReader.groovy deleted file mode 100644 index 25c1045fad0..00000000000 --- a/grails-spring/src/main/groovy/grails/spring/DynamicElementReader.groovy +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2004-2005 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 grails.spring - -import groovy.xml.StreamingMarkupBuilder -import org.apache.commons.logging.LogFactory -import org.codehaus.groovy.grails.commons.spring.BeanConfiguration -import org.springframework.beans.factory.config.BeanDefinitionHolder -import org.springframework.beans.factory.parsing.BeanDefinitionParsingException -import org.springframework.beans.factory.parsing.Location -import org.springframework.beans.factory.parsing.Problem -import org.springframework.beans.factory.xml.DefaultDocumentLoader -import org.springframework.beans.factory.xml.DelegatingEntityResolver -import org.springframework.beans.factory.xml.NamespaceHandler -import org.springframework.beans.factory.xml.ParserContext -import org.springframework.core.io.ByteArrayResource -import org.springframework.util.xml.SimpleSaxErrorHandler -import org.springframework.util.xml.XmlValidationModeDetector -import org.w3c.dom.Element -import org.xml.sax.EntityResolver -import org.xml.sax.ErrorHandler -import org.xml.sax.InputSource - -/** - * Used by BeanBuilder to read a Spring namespace expression in the Groovy DSL. - * - * @see BeanBuilder - * - * @author Graeme Rocher - * @since 1.1 - */ -class DynamicElementReader extends GroovyObjectSupport { - - private static final LOG = LogFactory.getLog(BeanBuilder) - - private Map xmlNamespaces - private String rootNamespace - ErrorHandler errorHandler = new SimpleSaxErrorHandler(LOG) - int validationMode = XmlValidationModeDetector.VALIDATION_NONE - EntityResolver entityResolver = new DelegatingEntityResolver(DynamicElementReader.class.getClassLoader()) - ParserContext parserContext - NamespaceHandler namespaceHandler - BeanConfiguration beanConfiguration - boolean beanDecorator = false - boolean firstCall = true - - DynamicElementReader(String namespace, Map namespaceMap=Collections.EMPTY_MAP, NamespaceHandler namespaceHandler = null, ParserContext parserContext = null) { - this.xmlNamespaces = namespaceMap - this.rootNamespace = namespace - this.namespaceHandler = namespaceHandler - this.parserContext = parserContext - } - - void setClassLoader(ClassLoader classLoader) { - entityResolver = new DelegatingEntityResolver(classLoader) - } - - /** - * Hook that subclass or anonymous classes can overwrite to implement custom behavior after invocation - * completes - */ - protected void afterInvocation() { - // NOOP - } - - @Override - Object invokeMethod(String name, Object args) { - boolean invokeAfterInterceptor = false - if (firstCall) { - invokeAfterInterceptor = true - firstCall = false - } - if (name.equals("doCall")) { - def callable = args[0] - callable.resolveStrategy = Closure.DELEGATE_FIRST - callable.delegate = this - def result = callable.call() - if (invokeAfterInterceptor) { - afterInvocation() - } - return result - } - - StreamingMarkupBuilder builder = new StreamingMarkupBuilder() - def myNamespaces = xmlNamespaces - def myNamespace = rootNamespace - - def callable = { - for (namespace in myNamespaces) { - mkp.declareNamespace([(namespace.key):namespace.value]) - } - if (args && (args[-1] instanceof Closure)) { - args[-1].resolveStrategy = Closure.DELEGATE_FIRST - args[-1].delegate = builder - } - delegate."$myNamespace"."$name"(*args) - } - - callable.resolveStrategy = Closure.DELEGATE_FIRST - callable.delegate = builder - def writable = builder.bind(callable) - - def sw = new StringWriter() - writable.writeTo(sw) - - def documentLoader = new DefaultDocumentLoader() - InputSource is = new InputSource(new StringReader(sw.toString())) - Element element = documentLoader.loadDocument(is, entityResolver, errorHandler, validationMode, true).getDocumentElement() - - parserContext?.delegate?.initDefaults element - if (namespaceHandler && parserContext) { - if (beanDecorator && beanConfiguration) { - BeanDefinitionHolder holder = new BeanDefinitionHolder(beanConfiguration.getBeanDefinition(), beanConfiguration.getName()) - holder = namespaceHandler.decorate(element,holder, parserContext) - beanConfiguration.setBeanDefinition(holder.getBeanDefinition()) - } - else { - def beanDefinition = namespaceHandler.parse(element, parserContext) - if (beanDefinition) { - beanConfiguration?.setBeanDefinition(beanDefinition) - } - } - } - else { - throw new BeanDefinitionParsingException(new Problem("No namespace handler found for element ${sw}", - new Location(parserContext?.readerContext?.resource ?: new ByteArrayResource(new byte[0])))) - } - - if (invokeAfterInterceptor) { - afterInvocation() - } - - return element - } -} diff --git a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/BeanConfiguration.java b/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/BeanConfiguration.java deleted file mode 100644 index beab206d00e..00000000000 --- a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/BeanConfiguration.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2004-2005 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.codehaus.groovy.grails.commons.spring; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.AbstractBeanDefinition; - -/** - * Represents a runtime bean configuration. - * - * Credit must go to Solomon Duskis and the - * article: http://jroller.com/page/Solomon?entry=programmatic_configuration_in_spring - * - * @author Graeme - * @since 0.3 - */ -public interface BeanConfiguration { - - String AUTOWIRE_BY_TYPE = "byType"; - String AUTOWIRE_BY_NAME = "byName"; - - /** - * @return The name of the bean - */ - String getName(); - - /** - * @return true if the bean is singleton - */ - boolean isSingleton(); - - /** - * @return The Spring bean definition instance - */ - AbstractBeanDefinition getBeanDefinition(); - - /** - * Adds a property value to this bean. - * @param propertyName The name of the property - * @param propertyValue The value of the property - * - * @return Returns this bean configuration - */ - BeanConfiguration addProperty(String propertyName, Object propertyValue); - - /** - * Sets the name of the method to call when destroying the bean. - * - * @param methodName The method name - * @return This bean configuration - */ - BeanConfiguration setDestroyMethod(String methodName); - - /** - * Sets the names of the beans this bean configuration depends on - * - * @param dependsOn Bean names it depends on - * @return This bean configuration - */ - BeanConfiguration setDependsOn(String[] dependsOn); - - /** - * - * @param beanName - * @return This BeanConfiguration - */ - BeanConfiguration setFactoryBean(String beanName); - - /** - * - * @param methodName - * @return This BeanConfiguration - */ - BeanConfiguration setFactoryMethod(String methodName); - - /** - * Sets the autowire type, either "byType" or "byName" - * - * @param type The type - * @return This BeanConfiguration - */ - BeanConfiguration setAutowire(String type); - - /** - * Sets the name of the bean in the app ctx. - * @param beanName The bean name - */ - void setName(String beanName); - - /** - * Returns true if the bean config has the name property set. - * @param name The name of the property - * @return true if it does have a property with the given name - */ - boolean hasProperty(String name); - - /** - * Returns the value of the given property or throws a MissingPropertyException. - * - * @param name The name of the property - * @return The value of the property - */ - Object getPropertyValue(String name); - - /** - * Sets a property value on the bean configuration - * - * @param property The name of the property - * @param newValue The value - */ - void setPropertyValue(String property, Object newValue); - - /** - * Sets the BeanConfiguration as an Abstract bean definition - * @param isAbstract Whether its abstract or not - * @return This BeanConfiguration object - */ - BeanConfiguration setAbstract(boolean isAbstract); - - /** - * Sets the name of the parent bean. - * - * @param name Either a string which is the name of the bean, a RuntimeBeanReference or a BeanConfiguration - */ - void setParent(Object name); - - void setBeanDefinition(BeanDefinition definition); -} diff --git a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultBeanConfiguration.java b/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultBeanConfiguration.java deleted file mode 100644 index 6ecf4ffa74d..00000000000 --- a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultBeanConfiguration.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright 2004-2005 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.codehaus.groovy.grails.commons.spring; - -import groovy.lang.GroovyObjectSupport; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.springframework.beans.BeanWrapper; -import org.springframework.beans.BeanWrapperImpl; -import org.springframework.beans.PropertyValue; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConstructorArgumentValues; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.util.Assert; - -/** - * Default implementation of the BeanConfiguration interface . - * - * Credit must go to Solomon Duskis and the - * article: http://jroller.com/page/Solomon?entry=programmatic_configuration_in_spring - * - * @author Graeme - * @since 0.3 - */ -public class DefaultBeanConfiguration extends GroovyObjectSupport implements BeanConfiguration { - - private static final String AUTOWIRE = "autowire"; - private static final String CONSTRUCTOR_ARGS = "constructorArgs"; - private static final String DESTROY_METHOD = "destroyMethod"; - private static final String FACTORY_BEAN = "factoryBean"; - private static final String FACTORY_METHOD = "factoryMethod"; - private static final String INIT_METHOD = "initMethod"; - private static final String BY_NAME = "byName"; - private static final String PARENT = "parent"; - private static final String BY_TYPE = "byType"; - private static final String BY_CONSTRUCTOR = "constructor"; - private static final List DYNAMIC_PROPS = Arrays.asList( - AUTOWIRE, - CONSTRUCTOR_ARGS, - DESTROY_METHOD, - FACTORY_BEAN, - FACTORY_METHOD, - INIT_METHOD, - BY_NAME, - BY_TYPE, - BY_CONSTRUCTOR); - - private String parentName; - - @Override - public Object getProperty(String property) { - @SuppressWarnings("unused") - AbstractBeanDefinition bd = getBeanDefinition(); - if (wrapper.isReadableProperty(property)) { - return wrapper.getPropertyValue(property); - } - if (DYNAMIC_PROPS.contains(property)) { - return null; - } - return super.getProperty(property); - } - - @Override - public void setProperty(String property, Object newValue) { - if (PARENT.equals(property)) { - setParent(newValue); - return; - } - - AbstractBeanDefinition bd = getBeanDefinition(); - if (AUTOWIRE.equals(property)) { - if (BY_NAME.equals(newValue)) { - bd.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME); - } - else if (BY_TYPE.equals(newValue)) { - bd.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE); - } - else if (Boolean.TRUE.equals(newValue)) { - bd.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME); - } - else if (BY_CONSTRUCTOR.equals(newValue)) { - bd.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR); - } - } - // constructorArgs - else if (CONSTRUCTOR_ARGS.equals(property) && newValue instanceof List) { - ConstructorArgumentValues cav = new ConstructorArgumentValues(); - for (Object e : (List)newValue) { - cav.addGenericArgumentValue(e); - } - bd.setConstructorArgumentValues(cav); - } - // destroyMethod - else if (DESTROY_METHOD.equals(property)) { - if (newValue != null) { - bd.setDestroyMethodName(newValue.toString()); - } - } - // factoryBean - else if (FACTORY_BEAN.equals(property)) { - if (newValue != null) { - bd.setFactoryBeanName(newValue.toString()); - } - } - // factoryMethod - else if (FACTORY_METHOD.equals(property)) { - if (newValue != null) { - bd.setFactoryMethodName(newValue.toString()); - } - } - // initMethod - else if (INIT_METHOD.equals(property)) { - if (newValue != null) { - bd.setInitMethodName(newValue.toString()); - } - } - else if (wrapper.isWritableProperty(property)) { - wrapper.setPropertyValue(property, newValue); - } - // autowire - else { - super.setProperty(property, newValue); - } - } - - private Class clazz; - private String name; - private boolean singleton = true; - private AbstractBeanDefinition definition; - private Collection constructorArgs = Collections.EMPTY_LIST; - private BeanWrapper wrapper; - - public DefaultBeanConfiguration(String name, Class clazz) { - this.name = name; - this.clazz = clazz; - } - - public DefaultBeanConfiguration(String name, Class clazz, boolean prototype) { - this(name,clazz,Collections.EMPTY_LIST); - singleton = !prototype; - } - - public DefaultBeanConfiguration(String name) { - this(name,null,Collections.EMPTY_LIST); - } - - public DefaultBeanConfiguration(Class clazz2) { - clazz = clazz2; - } - - public DefaultBeanConfiguration(String name2, Class clazz2, Collection args) { - name = name2; - clazz = clazz2; - constructorArgs = args; - } - - public DefaultBeanConfiguration(String name2, boolean prototype) { - this(name2,null,Collections.EMPTY_LIST); - singleton = !prototype; - } - - public DefaultBeanConfiguration(Class clazz2, Collection constructorArguments) { - clazz = clazz2; - constructorArgs = constructorArguments; - } - - public String getName() { - return name; - } - - public boolean isSingleton() { - return singleton; - } - - public AbstractBeanDefinition getBeanDefinition() { - if (definition == null) { - definition = createBeanDefinition(); - } - return definition; - } - - public void setBeanDefinition(BeanDefinition definition) { - this.definition = (AbstractBeanDefinition)definition; - } - - protected AbstractBeanDefinition createBeanDefinition() { - AbstractBeanDefinition bd = new GenericBeanDefinition(); - if (!constructorArgs.isEmpty()) { - ConstructorArgumentValues cav = new ConstructorArgumentValues(); - for (Object constructorArg : constructorArgs) { - cav.addGenericArgumentValue(constructorArg); - } - bd.setConstructorArgumentValues(cav); - } - bd.setBeanClass(clazz); - bd.setScope(singleton ? AbstractBeanDefinition.SCOPE_SINGLETON : AbstractBeanDefinition.SCOPE_PROTOTYPE); - if (parentName != null) { - bd.setParentName(parentName); - } - wrapper = new BeanWrapperImpl(bd); - return bd; - } - - public BeanConfiguration addProperty(String propertyName, Object propertyValue) { - if (propertyValue instanceof BeanConfiguration) { - propertyValue = ((BeanConfiguration)propertyValue).getBeanDefinition(); - } - getBeanDefinition() - .getPropertyValues() - .addPropertyValue(propertyName,propertyValue); - - return this; - } - - public BeanConfiguration setDestroyMethod(String methodName) { - getBeanDefinition().setDestroyMethodName(methodName); - return this; - } - - public BeanConfiguration setDependsOn(String[] dependsOn) { - getBeanDefinition().setDependsOn(dependsOn); - return this; - } - - public BeanConfiguration setFactoryBean(String beanName) { - getBeanDefinition().setFactoryBeanName(beanName); - return this; - } - - public BeanConfiguration setFactoryMethod(String methodName) { - getBeanDefinition().setFactoryMethodName(methodName); - return this; - } - - public BeanConfiguration setAutowire(String type) { - if ("byName".equals(type)) { - getBeanDefinition().setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME); - } - else if ("byType".equals(type)) { - getBeanDefinition().setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); - } - return this; - } - - public void setName(String beanName) { - name = beanName; - } - - public Object getPropertyValue(String propName) { - PropertyValue propertyValue = getBeanDefinition() - .getPropertyValues() - .getPropertyValue(propName); - if (propertyValue == null) { - return null; - } - - return propertyValue.getValue(); - } - - public boolean hasProperty(String propName) { - return getBeanDefinition().getPropertyValues().contains(propName); - } - - public void setPropertyValue(String property, Object newValue) { - getBeanDefinition().getPropertyValues().addPropertyValue(property, newValue); - } - - public BeanConfiguration setAbstract(boolean isAbstract) { - getBeanDefinition().setAbstract(isAbstract); - return this; - } - - public void setParent(Object obj) { - Assert.notNull(obj, "Parent bean cannot be set to a null runtime bean reference!"); - - if (obj instanceof String) { - parentName = (String)obj; - } - else if (obj instanceof RuntimeBeanReference) { - parentName = ((RuntimeBeanReference)obj).getBeanName(); - } - else if (obj instanceof BeanConfiguration) { - parentName = ((BeanConfiguration)obj).getName(); - } - getBeanDefinition().setParentName(parentName); - setAbstract(false); - } -} diff --git a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultRuntimeSpringConfiguration.java b/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultRuntimeSpringConfiguration.java deleted file mode 100644 index 570669c6a8b..00000000000 --- a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/DefaultRuntimeSpringConfiguration.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright 2004-2005 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.codehaus.groovy.grails.commons.spring; - -import groovy.lang.GroovySystem; -import groovy.lang.MetaClass; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.PropertyValue; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.util.Assert; - -/** - * A programmable runtime Spring configuration that allows a spring ApplicationContext - * to be constructed at runtime. - * - * Credit must go to Solomon Duskis and the - * article: http://jroller.com/page/Solomon?entry=programmatic_configuration_in_spring - * - * @author Graeme - * @since 0.3 - */ -public class DefaultRuntimeSpringConfiguration implements RuntimeSpringConfiguration { - - private static final Log LOG = LogFactory.getLog(DefaultRuntimeSpringConfiguration.class); - protected GenericApplicationContext context; - private Map beanConfigs = new HashMap(); - private Map beanDefinitions = new HashMap(); - private List beanNames = new ArrayList(); - protected ApplicationContext parent; - protected ClassLoader classLoader; - protected Map> aliases = new HashMap>(); - protected ListableBeanFactory beanFactory; - - /** - * Creates the ApplicationContext instance. Subclasses can override to customise the used ApplicationContext - * - * @param parentCtx The parent ApplicationContext instance. Can be null. - * - * @return An instance of GenericApplicationContext - */ - protected GenericApplicationContext createApplicationContext(ApplicationContext parentCtx) { - if (parentCtx != null && beanFactory != null) { - Assert.isInstanceOf(DefaultListableBeanFactory.class, beanFactory, - "ListableBeanFactory set must be a subclass of DefaultListableBeanFactory"); - - return new GrailsApplicationContext((DefaultListableBeanFactory) beanFactory,parentCtx); - } - - if (beanFactory != null) { - Assert.isInstanceOf(DefaultListableBeanFactory.class, beanFactory, - "ListableBeanFactory set must be a subclass of DefaultListableBeanFactory"); - - return new GrailsApplicationContext((DefaultListableBeanFactory) beanFactory); - } - - if (parentCtx != null) { - return new GrailsApplicationContext(parentCtx); - } - - return new GrailsApplicationContext(); - } - - public DefaultRuntimeSpringConfiguration() { - super(); - } - - public DefaultRuntimeSpringConfiguration(ApplicationContext parent) { - this(parent, null); - } - - public DefaultRuntimeSpringConfiguration(ApplicationContext parent, ClassLoader cl) { - this.parent = parent; - classLoader = cl; - } - - private void trySettingClassLoaderOnContextIfFoundInParent(ApplicationContext parentCtx) { - if (parentCtx.containsBean("classLoader")) { - Object cl = parentCtx.getBean("classLoader"); - if (cl instanceof ClassLoader) { - setClassLoaderOnContext((ClassLoader)cl); - } - } - } - - private void setClassLoaderOnContext(ClassLoader cl) { - context.setClassLoader(cl); - context.getBeanFactory().setBeanClassLoader(cl); - } - - /** - * Initialises the ApplicationContext instance. - */ - protected void initialiseApplicationContext() { - if (context != null) { - return; - } - - context = createApplicationContext(parent); - if (parent != null && classLoader == null) { - trySettingClassLoaderOnContextIfFoundInParent(parent); - } - else if (classLoader != null) { - setClassLoaderOnContext(classLoader); - } - - Assert.notNull(context); - } - - public BeanConfiguration addSingletonBean(String name, @SuppressWarnings("rawtypes") Class clazz) { - BeanConfiguration bc = new DefaultBeanConfiguration(name,clazz); - registerBeanConfiguration(name, bc); - return bc; - } - - public BeanConfiguration addPrototypeBean(String name, @SuppressWarnings("rawtypes") Class clazz) { - BeanConfiguration bc = new DefaultBeanConfiguration(name,clazz,true); - registerBeanConfiguration(name, bc); - return bc; - } - - public ApplicationContext getApplicationContext() { - long now = LOG.isDebugEnabled() ? System.currentTimeMillis() : 0; - initialiseApplicationContext(); - registerBeansWithContext(context); - context.refresh(); - if (LOG.isDebugEnabled()) { - LOG.debug("Created ApplicationContext in " + (System.currentTimeMillis() - now) + "ms"); - } - return context; - } - - public ApplicationContext getUnrefreshedApplicationContext() { - initialiseApplicationContext(); - return context; - } - - public BeanConfiguration addSingletonBean(String name) { - BeanConfiguration bc = new DefaultBeanConfiguration(name); - registerBeanConfiguration(name, bc); - return bc; - } - - public BeanConfiguration createSingletonBean(@SuppressWarnings("rawtypes") Class clazz) { - return new DefaultBeanConfiguration(clazz); - } - - @SuppressWarnings("rawtypes") - public BeanConfiguration addSingletonBean(String name, Class clazz, Collection args) { - BeanConfiguration bc = new DefaultBeanConfiguration(name,clazz,args); - registerBeanConfiguration(name, bc); - return bc; - } - - public BeanConfiguration addPrototypeBean(String name) { - BeanConfiguration bc = new DefaultBeanConfiguration(name,true); - registerBeanConfiguration(name, bc); - return bc; - } - - private void registerBeanConfiguration(String name, BeanConfiguration bc) { - beanConfigs.put(name,bc); - beanNames.add(name); - } - - @SuppressWarnings("rawtypes") - public BeanConfiguration createSingletonBean(Class clazz, Collection constructorArguments) { - return new DefaultBeanConfiguration(clazz, constructorArguments); - } - - public BeanConfiguration createPrototypeBean(String name) { - return new DefaultBeanConfiguration(name,true); - } - - public BeanConfiguration createSingletonBean(String name) { - return new DefaultBeanConfiguration(name); - } - - public void addBeanConfiguration(String beanName, BeanConfiguration beanConfiguration) { - beanConfiguration.setName(beanName); - registerBeanConfiguration(beanName, beanConfiguration); - } - - public void addBeanDefinition(String name, BeanDefinition bd) { - beanDefinitions.put(name,bd); - beanNames.add(name); - } - - public boolean containsBean(String name) { - return beanNames.contains(name); - } - - public BeanConfiguration getBeanConfig(String name) { - return beanConfigs.get(name); - } - - public AbstractBeanDefinition createBeanDefinition(String name) { - if (containsBean(name)) { - if (beanDefinitions.containsKey(name)) { - return (AbstractBeanDefinition)beanDefinitions.get(name); - } - if (beanConfigs.containsKey(name)) { - return beanConfigs.get(name).getBeanDefinition(); - } - } - return null; - } - - public void registerPostProcessor(BeanFactoryPostProcessor processor) { - initialiseApplicationContext(); - context.addBeanFactoryPostProcessor(processor); - } - - public List getBeanNames() { - return beanNames; - } - - public void registerBeansWithContext(GenericApplicationContext applicationContext) { - registerBeansWithRegistry(applicationContext); - } - - public void registerBeansWithRegistry(BeanDefinitionRegistry registry) { - registerUnrefreshedBeansWithRegistry(registry); - registerBeanConfigsWithRegistry(registry); - registerBeanDefinitionsWithRegistry(registry); - registerBeanAliasesWithRegistry(registry); - } - - private void registerUnrefreshedBeansWithRegistry(BeanDefinitionRegistry registry) { - if (context != null) { - for (String beanName : context.getBeanDefinitionNames()) { - registry.registerBeanDefinition(beanName, context.getBeanDefinition(beanName)); - } - } - } - - private void registerBeanConfigsWithRegistry(BeanDefinitionRegistry registry) { - for (BeanConfiguration bc : beanConfigs.values()) { - String beanName = bc.getName(); - if (LOG.isDebugEnabled()) { - LOG.debug("[RuntimeConfiguration] Registering bean [" + beanName + "]"); - if (LOG.isTraceEnabled()) { - PropertyValue[] pvs = bc.getBeanDefinition() - .getPropertyValues() - .getPropertyValues(); - for (PropertyValue pv : pvs) { - LOG.trace("[RuntimeConfiguration] With property [" + pv.getName() + "] set to [" + pv.getValue() + "]"); - } - } - } - - if (registry.containsBeanDefinition(beanName)) { - removeBeanDefinition(registry, beanName); - } - - registry.registerBeanDefinition(beanName, bc.getBeanDefinition()); - } - } - - private void registerBeanDefinitionsWithRegistry(BeanDefinitionRegistry registry) { - for (Object key : beanDefinitions.keySet()) { - BeanDefinition bd = beanDefinitions.get(key); - if (LOG.isDebugEnabled()) { - LOG.debug("[RuntimeConfiguration] Registering bean [" + key + "]"); - if (LOG.isTraceEnabled()) { - PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues(); - for (PropertyValue pv : pvs) { - LOG.trace("[RuntimeConfiguration] With property [" + pv.getName() + "] set to [" + pv.getValue() + "]"); - } - } - } - final String beanName = key.toString(); - if (registry.containsBeanDefinition(beanName)) { - removeBeanDefinition(registry, beanName); - } - - registry.registerBeanDefinition(beanName, bd); - } - } - - public void registerBeansWithConfig(RuntimeSpringConfiguration targetSpringConfig) { - if (targetSpringConfig == null) { - return; - } - - ApplicationContext ctx = targetSpringConfig.getUnrefreshedApplicationContext(); - if (ctx instanceof BeanDefinitionRegistry) { - final BeanDefinitionRegistry registry = (BeanDefinitionRegistry) ctx; - registerUnrefreshedBeansWithRegistry(registry); - registerBeansWithRegistry(registry); - } - for (Map.Entry beanEntry : beanConfigs.entrySet()) { - targetSpringConfig.addBeanConfiguration(beanEntry.getKey(), beanEntry.getValue()); - } - } - - private void registerBeanAliasesWithRegistry(BeanDefinitionRegistry beanDefinitionRegistry) { - for (Map.Entry> entry : aliases.entrySet()) { - String beanName = entry.getKey(); - List beanAliases = entry.getValue(); - if (beanAliases != null && !beanAliases.isEmpty()) { - for (String alias : beanAliases) { - beanDefinitionRegistry.registerAlias(beanName, alias); - } - } - } - } - - private void removeBeanDefinition(BeanDefinitionRegistry registry, String beanName) { - MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(registry.getClass()); - if (!mc.respondsTo(registry, "removeBeanDefinition").isEmpty()) { - mc.invokeMethod(registry, "removeBeanDefinition", new Object[] { beanName }); - } - } - - public BeanConfiguration addAbstractBean(String name) { - BeanConfiguration bc = new DefaultBeanConfiguration(name); - bc.setAbstract(true); - registerBeanConfiguration(name, bc); - return bc; - } - - public void addAlias(String alias, String beanName) { - List beanAliases = aliases.get(beanName); - if (beanAliases == null) { - beanAliases = new ArrayList(); - aliases.put(beanName, beanAliases); - } - beanAliases.add(alias); - } - - public BeanDefinition getBeanDefinition(String beanName) { - return beanDefinitions.get(beanName); - } - - public void setBeanFactory(ListableBeanFactory beanFactory) { - this.beanFactory = beanFactory; - } -} diff --git a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/RuntimeSpringConfiguration.java b/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/RuntimeSpringConfiguration.java deleted file mode 100644 index 2efa779d65a..00000000000 --- a/grails-spring/src/main/groovy/org/codehaus/groovy/grails/commons/spring/RuntimeSpringConfiguration.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright 2004-2005 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.codehaus.groovy.grails.commons.spring; - -import java.util.Collection; -import java.util.List; - -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericApplicationContext; - -/** - * A programmable runtime Spring configuration that allows a spring ApplicationContext - * to be constructed at runtime. - * - * Credit must go to Solomon Duskis and the - * article: http://jroller.com/page/Solomon?entry=programmatic_configuration_in_spring - * - * @author Graeme - * @since 0.3 - */ -public interface RuntimeSpringConfiguration { - - /** - * Adds a singleton bean definition. - * - * @param name The name of the bean - * @param clazz The class of the bean - * @return A BeanConfiguration instance - */ - BeanConfiguration addSingletonBean(String name, @SuppressWarnings("rawtypes") Class clazz); - - ApplicationContext getUnrefreshedApplicationContext(); - - /** - * Adds a prototype bean definition. - * - * @param name The name of the bean - * @param clazz The class of the bean - * @return A BeanConfiguration instance - */ - BeanConfiguration addPrototypeBean(String name, @SuppressWarnings("rawtypes") Class clazz); - - /** - * Retrieves the application context from the current state. - * - * @return The ApplicationContext instance - */ - ApplicationContext getApplicationContext(); - - /** - * Adds an empty singleton bean configuration. - * @param name The name of the singleton bean - * @return A BeanConfiguration instance - */ - BeanConfiguration addSingletonBean(String name); - - /** - * Adds an empty prototype bean configuration. - * - * @param name The name of the prototype bean - * @return A BeanConfiguration instance - */ - BeanConfiguration addPrototypeBean(String name); - - /** - * Creates a singleton bean configuration. Differs from addSingletonBean in that - * it doesn't add the bean to the list of bean references. Hence should be used for - * creating nested beans. - * - * @param clazz - * @return A BeanConfiguration instance - */ - BeanConfiguration createSingletonBean(@SuppressWarnings("rawtypes") Class clazz); - - /** - * Creates a new singleton bean and adds it to the list of bean references. - * - * @param name The name of the bean - * @param clazz The class of the bean - * @param args The constructor arguments of the bean - * @return A BeanConfiguration instance - */ - @SuppressWarnings("rawtypes") - BeanConfiguration addSingletonBean(String name, Class clazz, Collection args); - - /** - * Creates a singleton bean configuration. Differs from addSingletonBean in that - * it doesn't add the bean to the list of bean references. Hence should be used for - * creating nested beans - * - * @param clazz The bean class - * @param constructorArguments The constructor arguments - * @return A BeanConfiguration instance - */ - @SuppressWarnings("rawtypes") - BeanConfiguration createSingletonBean(Class clazz, Collection constructorArguments); - - /** - * Creates a new prototype bean configuration. Differs from addPrototypeBean in that - * it doesn't add the bean to the list of bean references to be created via the getApplicationContext() - * method, hence can be used for creating nested beans - * - * @param name The bean name - * @return A BeanConfiguration instance - */ - BeanConfiguration createPrototypeBean(String name); - - /** - * Creates a new singleton bean configuration. Differs from addSingletonBean in that - * it doesn't add the bean to the list of bean references to be created via the getApplicationContext() - * method, hence can be used for creating nested beans - * - * @param name The bean name - * @return A BeanConfiguration instance - * - */ - BeanConfiguration createSingletonBean(String name); - - /** - * Adds a bean configuration to the list of beans to be created. - * - * @param beanName The name of the bean in the context - * @param beanConfiguration The BeanConfiguration instance - */ - void addBeanConfiguration(String beanName, BeanConfiguration beanConfiguration); - - /** - * Adds a Spring BeanDefinition. Differs from BeanConfiguration which is a factory class - * for creating BeanDefinition instances - * @param name The name of the bean - * @param bd The BeanDefinition instance - */ - void addBeanDefinition(String name, BeanDefinition bd); - - /** - * Returns whether the runtime spring config contains the specified bean. - * - * @param name The bean name - * @return true if it does - */ - boolean containsBean(String name); - - /** - * Returns the BeanConfiguration for the specified name. - * @param name The name of the bean configuration - * @return The BeanConfiguration - */ - BeanConfiguration getBeanConfig(String name); - - /** - * Creates and returns the BeanDefinition that is regsitered within the given name or returns null. - * - * @param name The name of the bean definition - * @return A BeanDefinition - */ - AbstractBeanDefinition createBeanDefinition(String name); - - /** - * Registers a bean factory post processor with the context. - * - * @param processor The BeanFactoryPostProcessor instance - */ - void registerPostProcessor(BeanFactoryPostProcessor processor); - - List getBeanNames(); - - /** - * Registers the beans held within this RuntimeSpringConfiguration instance with the given ApplicationContext. - * - * @param applicationContext The ApplicationContext instance - */ - void registerBeansWithContext(GenericApplicationContext applicationContext); - - /** - * Registers the beans held within this RuntimeSpringConfiguration instance with the given BeanDefinitionRegistry. - * - * @param registry The BeanDefinitionRegistry instance - */ - void registerBeansWithRegistry(BeanDefinitionRegistry registry); - - /** - * Registers the beans held within this RuntimeSpringConfiguration instance with the given RuntimeSpringConfiguration. - * - * @param targetSpringConfig The RuntimeSpringConfiguration instance - */ - void registerBeansWithConfig(RuntimeSpringConfiguration targetSpringConfig); - - /** \ - * Adds an abstract bean definition to the bean factory and returns the BeanConfiguration object. - * - * @param name The name of the bean - * @return The BeanConfiguration object - */ - BeanConfiguration addAbstractBean(String name); - - /** - * Adds an alias to a given bean name. - * - * @param alias The alias - * @param beanName The bean - */ - void addAlias(String alias, String beanName); - - /** - * Obtains a BeanDefinition instance for the given beanName. - * - * @param beanName The beanName - * @return The BeanDefinition or null if it doesn't exit - */ - BeanDefinition getBeanDefinition(String beanName); - - /** - * Sets the BeanFactory implementation to use. - * @param beanFactory The BeanFactory implementation - */ - void setBeanFactory(ListableBeanFactory beanFactory); -} diff --git a/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/support/TransactionManagerPostProcessorTests.groovy b/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/support/TransactionManagerPostProcessorTests.groovy index f083ffb883f..a90ee2fbcb9 100644 --- a/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/support/TransactionManagerPostProcessorTests.groovy +++ b/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/support/TransactionManagerPostProcessorTests.groovy @@ -1,7 +1,6 @@ package org.codehaus.groovy.grails.orm.support -import grails.spring.BeanBuilder - +import org.springframework.context.groovy.GroovyBeanDefinitionReader import org.springframework.jdbc.datasource.DataSourceTransactionManager import org.springframework.jdbc.datasource.DriverManagerDataSource import org.springframework.transaction.PlatformTransactionManager @@ -13,7 +12,7 @@ import org.springframework.transaction.PlatformTransactionManager class TransactionManagerPostProcessorTests extends GroovyTestCase{ void testTransactionManagerPostProccessor() { - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() bb.beans { myBean(MyBean) { bean -> diff --git a/grails-test-suite-uber/src/test/groovy/grails/spring/BeanBuilderTests.groovy b/grails-test-suite-uber/src/test/groovy/grails/spring/BeanBuilderTests.groovy deleted file mode 100644 index 4bf9b536a75..00000000000 --- a/grails-test-suite-uber/src/test/groovy/grails/spring/BeanBuilderTests.groovy +++ /dev/null @@ -1,934 +0,0 @@ -/* - * Copyright 2004-2005 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 grails.spring - -import org.codehaus.groovy.grails.plugins.PluginManagerHolder -import org.springframework.aop.SpringProxy -import org.springframework.beans.factory.BeanIsAbstractException -import org.springframework.beans.factory.ObjectFactory -import org.springframework.beans.factory.config.Scope -import org.springframework.context.ApplicationContext -import org.springframework.context.support.GenericApplicationContext -import org.springframework.core.io.support.PathMatchingResourcePatternResolver -import org.springframework.stereotype.Component - -/** - * @author Graeme Rocher - * @since 0.4 - */ -class BeanBuilderTests extends GroovyTestCase { - - private BeanBuilder bb = new BeanBuilder() - - @Override - protected void setUp() { - super.setUp() - PluginManagerHolder.setPluginManager null - } - - void testImportSpringXml() { - - bb.beans { - importBeans "classpath:grails/spring/test.xml" - } - - def ctx = bb.createApplicationContext() - - def foo = ctx.getBean("foo") - assertEquals "hello", foo - } - - void testImportBeansFromGroovy() { - - bb.beans { - importBeans "file:test/resources/spring/test.groovy" - } - - def ctx = bb.createApplicationContext() - - def foo = ctx.getBean("foo") - assertEquals "hello", foo - } - - void testInheritPropertiesFromAbstractBean() { - - bb.beans { - myB(Bean1) { - person = "wombat" - } - - myAbstractA(Bean2) { bean -> - bean.'abstract' = true - age = 10 - bean1 = myB - } - myConcreteB { - it.parent = myAbstractA - } - } - - def ctx = bb.createApplicationContext() - def bean = ctx.getBean("myConcreteB") - - assertEquals 10, bean.age - assertNotNull bean.bean1 - } - - void testContextComponentScanSpringTag() { - - bb.beans { - xmlns grailsContext:"http://grails.org/schema/context" - - grailsContext.'component-scan'('base-package' :"**") - } - - def appCtx = bb.createApplicationContext() - - def p = appCtx.getBean("person") - - assertTrue(p instanceof AdvisedPerson) - assertNotNull p - } - - void testUseSpringNamespaceAsMethod() { - - bb.beans { - xmlns aop:"http://www.springframework.org/schema/aop" - - fred(AdvisedPerson) { - name = "Fred" - age = 45 - } - birthdayCardSenderAspect(BirthdayCardSender) - - aop { - config("proxy-target-class":true) { - aspect(id:"sendBirthdayCard",ref:"birthdayCardSenderAspect") { - after method:"onBirthday", pointcut: "execution(void grails.spring.AdvisedPerson.birthday()) and this(person)" - } - } - } - } - - def appCtx = bb.createApplicationContext() - def fred = appCtx.getBean("fred") - assertTrue (fred instanceof SpringProxy) - - fred.birthday() - - BirthdayCardSender birthDaySender = appCtx.getBean("birthdayCardSenderAspect") - - assertEquals 1, birthDaySender.peopleSentCards.size() - assertEquals "Fred", birthDaySender.peopleSentCards[0].name - } - - void testUseTwoSpringNamespaces() { - - TestScope scope = new TestScope() - - GenericApplicationContext appCtx = bb.getSpringConfig().getUnrefreshedApplicationContext() - appCtx.getBeanFactory().registerScope("test", scope) - bb.beans { - xmlns aop:"http://www.springframework.org/schema/aop" - xmlns util:"http://www.springframework.org/schema/util" - scopedList(ArrayList) { bean -> - bean.scope = "test" - aop.'scoped-proxy'() - } - - util.list(id:"foo") { - value "one" - value "two" - } - - } - - appCtx = bb.createApplicationContext() - - assert ['one', 'two'] == appCtx.getBean("foo") - - assertNotNull appCtx.getBean("scopedList") - assertNotNull appCtx.getBean("scopedList").size() - assertNotNull appCtx.getBean("scopedList").size() - - // should only be true because bean not initialized until proxy called - assertEquals 2, scope.instanceCount - - bb = new BeanBuilder() - - appCtx = bb.getSpringConfig().getUnrefreshedApplicationContext() - appCtx.getBeanFactory().registerScope("test", scope) - bb.beans { - xmlns aop:"http://www.springframework.org/schema/aop", - util:"http://www.springframework.org/schema/util" - scopedList(ArrayList) { bean -> - bean.scope = "test" - aop.'scoped-proxy'() - } - - util.list(id:"foo") { - value "one" - value "two" - } - - } - appCtx = bb.createApplicationContext() - - assert ['one', 'two'] == appCtx.getBean("foo") - - assertNotNull appCtx.getBean("scopedList") - assertNotNull appCtx.getBean("scopedList").size() - assertNotNull appCtx.getBean("scopedList").size() - - // should only be true because bean not initialized until proxy called - assertEquals 4, scope.instanceCount - } - - void testSpringAOPSupport() { - - bb.beans { - xmlns aop:"http://www.springframework.org/schema/aop" - - fred(AdvisedPerson) { - name = "Fred" - age = 45 - } - birthdayCardSenderAspect(BirthdayCardSender) - - aop.config("proxy-target-class":true) { - aspect(id:"sendBirthdayCard",ref:"birthdayCardSenderAspect") { - after method:"onBirthday", pointcut: "execution(void grails.spring.AdvisedPerson.birthday()) and this(person)" - } - } - } - - def appCtx = bb.createApplicationContext() - def fred = appCtx.getBean("fred") - assertTrue (fred instanceof SpringProxy) - - fred.birthday() - - BirthdayCardSender birthDaySender = appCtx.getBean("birthdayCardSenderAspect") - - assertEquals 1, birthDaySender.peopleSentCards.size() - assertEquals "Fred", birthDaySender.peopleSentCards[0].name - } - - void testSpringScopedProxyBean() { - - GenericApplicationContext appCtx = bb.getSpringConfig().getUnrefreshedApplicationContext() - TestScope scope = new TestScope() - appCtx.getBeanFactory().registerScope("test", scope) - bb.beans { - xmlns aop:"http://www.springframework.org/schema/aop" - scopedList(ArrayList) { bean -> - bean.scope = "test" - aop.'scoped-proxy'() - } - } - - appCtx = bb.createApplicationContext() - - assertNotNull appCtx.getBean("scopedList") - assertNotNull appCtx.getBean("scopedList").size() - assertNotNull appCtx.getBean("scopedList").size() - - // should only be true because bean not initialized until proxy called - assertEquals 2, scope.instanceCount - } - - void testSpringNamespaceBean() { - bb.beans { - xmlns util:"http://www.springframework.org/schema/util" - util.list(id:"foo") { - value "one" - value "two" - } - - } - - ApplicationContext appCtx = bb.createApplicationContext() - - assert ['one', 'two'] == appCtx.getBean("foo") - } - - void testNamedArgumentConstructor() { - bb.beans { - holyGrail(HolyGrailQuest) - knights(KnightOfTheRoundTable, "Camelot", leader:"lancelot", quest: holyGrail) - } - - def ctx = bb.createApplicationContext() - - KnightOfTheRoundTable knights = ctx.getBean("knights") - HolyGrailQuest quest = ctx.getBean("holyGrail") - - assertEquals "Camelot", knights.name - assertEquals "lancelot", knights.leader - assertEquals quest, knights.quest - } - - void testAbstractBeanDefinition() { - bb.beans { - abstractBean { - leader = "Lancelot" - } - quest(HolyGrailQuest) - knights(KnightOfTheRoundTable, "Camelot") { bean -> - bean.parent = abstractBean - quest = quest - } - } - def ctx = bb.createApplicationContext() - - def knights = ctx.knights - assert knights - shouldFail(org.springframework.beans.factory.BeanIsAbstractException) { - ctx.abstractBean - } - assertEquals "Lancelot", knights.leader - } - - void testAbstractBeanDefinitionWithClass() { - bb.beans { - abstractBean(KnightOfTheRoundTable) { bean -> - bean.'abstract' = true - leader = "Lancelot" - } - quest(HolyGrailQuest) - knights("Camelot") { bean -> - bean.parent = abstractBean - quest = quest - } - } - def ctx = bb.createApplicationContext() - - shouldFail(BeanIsAbstractException) { - ctx.abstractBean - } - def knights = ctx.knights - assert knights - assertEquals "Lancelot", knights.leader - } - - void testScopes() { - bb.beans { - myBean(ScopeTest) { bean -> - bean.scope = "prototype" - } - myBean2(ScopeTest) - } - def ctx = bb.createApplicationContext() - - def b1 = ctx.myBean - def b2 = ctx.myBean - - assert b1 != b2 - - b1 = ctx.myBean2 - b2 = ctx.myBean2 - - assertEquals b1, b2 - } - - void testSimpleBean() { - bb.beans { - bean1(Bean1) { - person = "homer" - age = 45 - props = [overweight:true, height:"1.8m"] - children = ["bart", "lisa"] - } - } - def ctx = bb.createApplicationContext() - - assert ctx.containsBean("bean1") - def bean1 = ctx.getBean("bean1") - - assertEquals "homer", bean1.person - assertEquals 45, bean1.age - assertEquals true, bean1.props?.overweight - assertEquals "1.8m", bean1.props?.height - assertEquals(["bart", "lisa"], bean1.children) - } - - void testBeanWithParentRef() { - bb.beans { - homer(Bean1) { - person = "homer" - age = 45 - props = [overweight:true, height:"1.8m"] - children = ["bart", "lisa"] - } - } - bb = new BeanBuilder(bb.createApplicationContext()) - bb.beans { - bart(Bean2) { - person = "bart" - parent = ref("homer", true) - } - } - - def ctx = bb.createApplicationContext() - assert ctx != null - assert ctx.containsBean("bart") - def bart = ctx.getBean("bart") - assertEquals "homer",bart.parent?.person - } - - void testWithAnonymousInnerBean() { - bb.beans { - bart(Bean1) { - person = "bart" - age = 11 - } - lisa(Bean1) { - person = "lisa" - age = 9 - } - marge(Bean2) { - person = "marge" - bean1 = { Bean1 b -> - person = "homer" - age = 45 - props = [overweight:true, height:"1.8m"] - children = ["bart", "lisa"] - } - children = [bart, lisa] - } - } - - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assertEquals "homer", marge.bean1.person - } - - void testAnonymousInnerBeanViaBeanMethod() { - bb.beans { - bart(Bean1) { - person = "bart" - age = 11 - } - lisa(Bean1) { - person = "lisa" - age = 9 - } - marge(Bean2) { - person = "marge" - bean1 = bean(Bean1) { - person = "homer" - age = 45 - props = [overweight:true, height:"1.8m"] - children = ["bart", "lisa"] - } - children = [bart, lisa] - } - } - - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assertEquals "homer", marge.bean1.person - } - - void testAnonymousInnerBeanViaBeanMethodWithConstructorArgs() { - bb.beans { - bart(Bean1) { - person = "bart" - age = 11 - } - lisa(Bean1) { - person = "lisa" - age = 9 - } - marge(Bean2) { - person = "marge" - bean3 = bean(Bean3, "homer", lisa) { - person = "homer" - age = 45 - } - children = [bart, lisa] - } - } - - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assertEquals "homer", marge.bean3.person - assertEquals "lisa", marge.bean3.bean1.person - } - - void testWithUntypedAnonymousInnerBean() { - bb.beans { - homer(Bean1Factory) - bart(Bean1) { - person = "bart" - age = 11 - } - lisa(Bean1) { - person = "lisa" - age = 9 - } - marge(Bean2) { - person = "marge" - bean1 = { bean -> - bean.factoryBean = "homer" - bean.factoryMethod = "newInstance" - person = "homer" - } - children = [bart, lisa] - } - } - - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assertEquals "homer", marge.bean1.person - } - - void testBeanReferences() { - bb.beans { - homer(Bean1) { - person = "homer" - age = 45 - props = [overweight:true, height:"1.8m"] - children = ["bart", "lisa"] - } - bart(Bean1) { - person = "bart" - age = 11 - } - lisa(Bean1) { - person = "lisa" - age = 9 - } - marge(Bean2) { - person = "marge" - bean1 = homer - children = [bart, lisa] - } - } - def ctx = bb.createApplicationContext() - - def homer = ctx.getBean("homer") - def marge = ctx.getBean("marge") - def bart = ctx.getBean("bart") - def lisa = ctx.getBean("lisa") - - assertEquals homer, marge.bean1 - assertEquals 2, marge.children.size() - - assertTrue marge.children.contains(bart) - assertTrue marge.children.contains(lisa) - } - - void testBeanWithConstructor() { - bb.beans { - homer(Bean1) { - person = "homer" - age = 45 - } - marge(Bean3, "marge", homer) { - age = 40 - } - } - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assertEquals "marge", marge.person - assertEquals "homer", marge.bean1.person - assertEquals 40, marge.age - } - - void testBeanWithListAndMapConstructor() { - bb.beans { - bart(Bean1) { - person = "bart" - age = 11 - } - lisa(Bean1) { - person = "lisa" - age = 9 - } - - beanWithList(Bean5, [bart, lisa]) - - // test runtime references both as ref() and as plain name - beanWithMap(Bean6, [bart:bart, lisa:ref('lisa')]) - } - def ctx = bb.createApplicationContext() - - def beanWithList = ctx.getBean("beanWithList") - assertEquals 2, beanWithList.people.size() - assertEquals "bart", beanWithList.people[0].person - - def beanWithMap = ctx.getBean("beanWithMap") - assertEquals 9, beanWithMap.peopleByName.lisa.age - assertEquals "bart", beanWithMap.peopleByName.bart.person - } - - void testBeanWithFactoryMethod() { - bb.beans { - homer(Bean1) { - person = "homer" - age = 45 - } - def marge = marge(Bean4) { - person = "marge" - } - marge.factoryMethod = "getInstance" - } - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assert "marge", marge.person - } - - void testBeanWithFactoryMethodUsingClosureArgs() { - bb.beans { - homer(Bean1) { - person = "homer" - age = 45 - } - marge(Bean4) { bean -> - bean.factoryMethod = "getInstance" - person = "marge" - } - } - def ctx = bb.createApplicationContext() - - def marge = ctx.getBean("marge") - - assert "marge", marge.person - } - void testBeanWithFactoryMethodWithConstructorArgs() { - bb.beans { - beanFactory(Bean1FactoryWithArgs) {} - - homer(beanFactory:"newInstance", "homer") { - age = 45 - } - //Test with no closure body - marge(beanFactory:"newInstance", "marge") - - //Test more verbose method - mcBain("mcBain") { - bean -> - bean.factoryBean="beanFactory" - bean.factoryMethod="newInstance" - - } - } - def ctx = bb.createApplicationContext() - - def homer = ctx.getBean("homer") - - assert "homer", homer.person - assert 45, homer.age - - assert "marge", ctx.getBean("marge").person - - assert "mcBain", ctx.getBean("mcBain").person - } - - void testGetBeanDefinitions() { - bb.beans { - jeff(Bean1) { - person = 'jeff' - } - graeme(Bean1) { - person = 'graeme' - } - guillaume(Bean1) { - person = 'guillaume' - } - } - - def beanDefinitions = bb.beanDefinitions - assertNotNull 'beanDefinitions was null', beanDefinitions - assertEquals 'beanDefinitions was the wrong size', 3, beanDefinitions.size() - assertNotNull 'beanDefinitions did not contain jeff', beanDefinitions['jeff'] - assertNotNull 'beanDefinitions did not contain guillaume', beanDefinitions['guillaume'] - assertNotNull 'beanDefinitions did not contain graeme', beanDefinitions['graeme'] - } - - void testBeanWithFactoryBean() { - bb.beans { - myFactory(Bean1Factory) - - homer(myFactory) { bean -> - bean.factoryMethod = "newInstance" - person = "homer" - age = 45 - } - } - - def ctx = bb.createApplicationContext() - - def homer = ctx.getBean("homer") - - assertEquals "homer", homer.person - } - - void testBeanWithFactoryBeanAndMethod() { - bb.beans { - myFactory(Bean1Factory) - - homer(myFactory:"newInstance") { bean -> - person = "homer" - age = 45 - } - } - - def ctx = bb.createApplicationContext() - - def homer = ctx.getBean("homer") - - assertEquals "homer", homer.person - } - - void testLoadExternalBeans() { - def pr = new PathMatchingResourcePatternResolver() - def r = pr.getResource("grails/spring/resources1.groovy") - - bb.loadBeans(r) - - def ctx = bb.createApplicationContext() - - assert ctx.containsBean("dataSource") - - def dataSource = ctx.getBean("dataSource") - } - - void testHolyGrailWiring() { - - bb.beans { - quest(HolyGrailQuest) - - knight(KnightOfTheRoundTable, "Bedivere") { - quest = ref("quest") - } - } - - def ctx = bb.createApplicationContext() - - def knight = ctx.getBean("knight") - - knight.embarkOnQuest() - } - - void testAbstractBeanSpecifyingClass() { - - bb.beans { - abstractKnight(KnightOfTheRoundTable) { bean -> - bean.'abstract' = true - leader = "King Arthur" - } - - lancelot("lancelot") { bean -> - bean.parent = ref("abstractKnight") - } - - abstractPerson(Bean1) { bean -> - bean.'abstract'=true - age = 45 - } - homerBean { bean -> - bean.parent = ref("abstractPerson") - person = "homer" - } - } - - def ctx = bb.createApplicationContext() - - def lancelot = ctx.getBean("lancelot") - assertEquals "King Arthur", lancelot.leader - assertEquals "lancelot", lancelot.name - - def homerBean = ctx.getBean("homerBean") - - assertEquals 45, homerBean.age - assertEquals "homer", homerBean.person - } - - void testBeanBuilderWithScript() { - def script = ''' -def bb = new grails.spring.BeanBuilder() - -bb.beans { -quest(grails.spring.HolyGrailQuest) {} - -knight(grails.spring.KnightOfTheRoundTable, "Bedivere") { quest = quest } -} -bb.createApplicationContext() - ''' - def ctx = new GroovyShell().evaluate(script) - - def knight = ctx.getBean('knight') - knight.embarkOnQuest() - } - - // test for GRAILS-5057 - void testRegisterBeans() { - - bb.beans { - personA(AdvisedPerson) { - name = "Bob" - } - } - - def appCtx = bb.createApplicationContext() - - assertEquals "Bob", appCtx.getBean("personA").name - - bb = new BeanBuilder() - bb.beans { - personA(AdvisedPerson) { - name = "Fred" - } - } - bb.registerBeans(appCtx) - - assertEquals "Fred", appCtx.getBean("personA").name - } -} - -class HolyGrailQuest { - void start() { println "lets begin" } -} - -class KnightOfTheRoundTable { - String name - String leader - KnightOfTheRoundTable(String n) { - this.name = n - } - HolyGrailQuest quest - - void embarkOnQuest() { - quest.start() - } -} - -// simple bean -class Bean1 { - String person - int age - Properties props - List children -} - -// bean referencing other bean -class Bean2 { - int age - String person - Bean1 bean1 - Bean3 bean3 - Properties props - List children - Bean1 parent -} - -// bean with constructor args -class Bean3 { - Bean3(String person, Bean1 bean1) { - this.person = person - this.bean1 = bean1 - } - String person - Bean1 bean1 - int age -} - -// bean with factory method -class Bean4 { - private Bean4() {} - static Bean4 getInstance() { new Bean4() } - String person -} - -// bean with List-valued constructor arg -class Bean5 { - Bean5(List people) { - this.people = people - } - List people -} - -// bean with Map-valued constructor arg -class Bean6 { - Bean6(Map peopleByName) { - this.peopleByName = peopleByName - } - Map peopleByName -} - -// a factory bean -class Bean1Factory { - Bean1 newInstance() { new Bean1() } -} - -class ScopeTest {} - -class TestScope implements Scope { - - int instanceCount - - Object remove(String name) { - // do nothing - } - - void registerDestructionCallback(String name, Runnable callback) {} - - String getConversationId() { "mock" } - - Object get(String name, ObjectFactory objectFactory) { - instanceCount++ - objectFactory.getObject() - } - - Object resolveContextualObject(String s) { null } -} - -class BirthdayCardSender { - List peopleSentCards = [] - void onBirthday(AdvisedPerson person) { - peopleSentCards << person - } -} - -@Component(value = "person") -class AdvisedPerson { - int age - String name - - void birthday() { - ++age - } -} -// a factory bean that takes arguments -class Bean1FactoryWithArgs { - Bean1 newInstance(String name) { - new Bean1(person:name) - } -} diff --git a/grails-test-suite-uber/src/test/groovy/grails/spring/DynamicElementReaderTests.groovy b/grails-test-suite-uber/src/test/groovy/grails/spring/DynamicElementReaderTests.groovy deleted file mode 100644 index 381e915b507..00000000000 --- a/grails-test-suite-uber/src/test/groovy/grails/spring/DynamicElementReaderTests.groovy +++ /dev/null @@ -1,23 +0,0 @@ -package grails.spring - -import org.w3c.dom.Element - -/** - * @author Graeme Rocher - * @since 1.0 - */ -class DynamicElementReaderTests extends GroovyTestCase { - - void testReadMethodToElement() { - - def elementReader = new DynamicElementReader("jee", [jee:"http://www.springframework.org/schema/jee"]) - - try { - elementReader.'jndi-lookup'(id:"dataSource", 'jndi-name':"jdbc/petstore") - } - catch (e) { - assertEquals """Configuration problem: No namespace handler found for element -Offending resource: resource loaded from byte array""", e.message - } - } -} diff --git a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfiguratorTests.java b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfiguratorTests.java index 59928b1b42b..8ee728be738 100644 --- a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfiguratorTests.java +++ b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfiguratorTests.java @@ -18,6 +18,9 @@ import org.codehaus.groovy.grails.web.errors.GrailsExceptionResolver; import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; +import org.springframework.context.groovy.BeanConfiguration; +import org.springframework.context.groovy.DefaultRuntimeSpringConfiguration; +import org.springframework.context.groovy.RuntimeSpringConfiguration; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; diff --git a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPluginTests.java b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPluginTests.java index 9a50fdff558..cf99c6c42ca 100644 --- a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPluginTests.java +++ b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/DefaultGrailsPluginTests.java @@ -15,13 +15,13 @@ */ package org.codehaus.groovy.grails.plugins; -import org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration; -import org.codehaus.groovy.grails.commons.spring.RuntimeSpringConfiguration; +import java.io.File; + import org.codehaus.groovy.grails.commons.test.AbstractGrailsMockTests; import org.codehaus.groovy.grails.plugins.exceptions.PluginException; import org.springframework.context.ApplicationContext; - -import java.io.File; +import org.springframework.context.groovy.DefaultRuntimeSpringConfiguration; +import org.springframework.context.groovy.RuntimeSpringConfiguration; /** * Test for the DefaultGrailsPlugin class diff --git a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPluginTests.groovy b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPluginTests.groovy index 043af1b965d..ed774d1fd8e 100644 --- a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPluginTests.groovy +++ b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPluginTests.groovy @@ -1,6 +1,5 @@ package org.codehaus.groovy.grails.plugins.datasource -import grails.spring.BeanBuilder import grails.util.Holders import groovy.sql.Sql @@ -9,6 +8,7 @@ import javax.sql.DataSource import org.apache.tomcat.jdbc.pool.DataSource as TomcatDataSource import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator import org.codehaus.groovy.grails.commons.test.AbstractGrailsMockTests +import org.springframework.context.groovy.GroovyBeanDefinitionReader import org.springframework.jdbc.datasource.DriverManagerDataSource import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy @@ -466,8 +466,8 @@ class DataSourceGrailsPluginTests extends AbstractGrailsMockTests { configurator.configure(ctx.getServletContext()) } - private BeanBuilder createBeanBuilder(config) { - def bb = new BeanBuilder(binding: new Binding([application: [config: config]])) + private GroovyBeanDefinitionReader createBeanBuilder(config) { + def bb = new GroovyBeanDefinitionReader(binding: new Binding([application: [config: config]])) bb.beans new DataSourceGrailsPlugin().doWithSpring bb } diff --git a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/web/ControllersGrailsPluginTests.groovy b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/web/ControllersGrailsPluginTests.groovy index 2ae39095ff4..91e45bb5d2b 100644 --- a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/web/ControllersGrailsPluginTests.groovy +++ b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/plugins/web/ControllersGrailsPluginTests.groovy @@ -1,9 +1,10 @@ package org.codehaus.groovy.grails.plugins.web -import grails.spring.BeanBuilder import grails.util.GrailsWebUtil + import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator import org.springframework.beans.factory.NoSuchBeanDefinitionException +import org.springframework.context.groovy.GroovyBeanDefinitionReader import org.springframework.web.multipart.commons.CommonsMultipartResolver class ControllersGrailsPluginTests extends AbstractGrailsPluginTests { @@ -123,7 +124,7 @@ class FormTagLib { def mock = [application: [flatConfig: new ConfigObject(), config: new ConfigObject(), warDeployed: false], manager:mockManager] def plugin = new GroovyPagesGrailsPlugin() def beans = plugin.doWithSpring - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() bb.setBinding(new Binding(mock)) bb.beans(beans) def beanDef = bb.getBeanDefinition('groovyPageResourceLoader') @@ -147,7 +148,7 @@ class FormTagLib { def mock = [application: [config: new ConfigObject(), warDeployed: true],manager:mockManager] def plugin = new ControllersGrailsPlugin() def beans = plugin.doWithSpring - def bb = new BeanBuilder() + def bb = new GroovyBeanDefinitionReader() bb.setBinding(new Binding(mock)) bb.beans(beans) assertNull bb.getBeanDefinition('groovyPageResourceLoader') diff --git a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/reload/SpringProxiedBeanReloadTests.groovy b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/reload/SpringProxiedBeanReloadTests.groovy index e206bfb9449..a92644c4940 100644 --- a/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/reload/SpringProxiedBeanReloadTests.groovy +++ b/grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/reload/SpringProxiedBeanReloadTests.groovy @@ -1,9 +1,9 @@ package org.codehaus.groovy.grails.reload -import grails.spring.BeanBuilder -import org.springframework.aop.framework.ProxyFactoryBean import org.aopalliance.intercept.MethodInterceptor import org.aopalliance.intercept.MethodInvocation +import org.springframework.aop.framework.ProxyFactoryBean +import org.springframework.context.groovy.GroovyBeanDefinitionReader /** * @author Graeme Rocher @@ -15,7 +15,7 @@ class SpringProxiedBeanReloadTests extends GroovyTestCase { def gcl = new GroovyClassLoader() def cls = gcl.parseClass("class Book { String title = 'The Stand'; String author }") - def bb = new BeanBuilder(gcl) + def bb = new GroovyBeanDefinitionReader(gcl) bb.beans { interceptor(DummyInterceptor) target(cls) { @@ -36,7 +36,7 @@ class SpringProxiedBeanReloadTests extends GroovyTestCase { gcl = new GroovyClassLoader() cls = gcl.parseClass("class Book { String title = 'The Shining'; String author }") - bb = new BeanBuilder(gcl) + bb = new GroovyBeanDefinitionReader(gcl) bb.beans { interceptor(DummyInterceptor) target(cls) { diff --git a/grails-test-suite-web/src/test/groovy/grails/gsp/PageRendererSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/gsp/PageRendererSpec.groovy index 8694398c626..f0ed3bd4362 100644 --- a/grails-test-suite-web/src/test/groovy/grails/gsp/PageRendererSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/gsp/PageRendererSpec.groovy @@ -1,7 +1,5 @@ package grails.gsp -import grails.spring.BeanBuilder - import org.codehaus.groovy.grails.commons.DefaultGrailsApplication import org.codehaus.groovy.grails.commons.TagLibArtefactHandler import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib @@ -9,6 +7,7 @@ import org.codehaus.groovy.grails.support.SimpleMapResourceLoader import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine import org.codehaus.groovy.grails.web.pages.TagLibraryLookup import org.codehaus.groovy.grails.web.pages.discovery.CachingGrailsConventionGroovyPageLocator +import org.springframework.context.groovy.GroovyBeanDefinitionReader import org.springframework.core.io.ByteArrayResource import spock.lang.Specification @@ -112,7 +111,7 @@ class PageRendererSpec extends Specification { te.afterPropertiesSet() def renderer = new PageRenderer(te) - def bb = new BeanBuilder().beans { + def bb = new GroovyBeanDefinitionReader().beans { grailsApplication(DefaultGrailsApplication) "${ApplicationTagLib.name}"(ApplicationTagLib) { grailsApplication = ref('grailsApplication')