Example usage for org.springframework.beans.factory.support RootBeanDefinition setPropertyValues

List of usage examples for org.springframework.beans.factory.support RootBeanDefinition setPropertyValues

Introduction

In this page you can find the example usage for org.springframework.beans.factory.support RootBeanDefinition setPropertyValues.

Prototype

public void setPropertyValues(MutablePropertyValues propertyValues) 

Source Link

Document

Specify property values for this bean, if any.

Usage

From source file:org.springmodules.cache.config.AbstractCacheManagerAndProviderFacadeParser.java

/**
 * Parses the given XML element containing the properties of the cache manager
 * to register in the given registry of bean definitions.
 * /*from   ww w . j a v  a  2s  .  c  om*/
 * @param element
 *          the XML element to parse
 * @param registry
 *          the registry of bean definitions
 * 
 * @see AbstractCacheProviderFacadeParser#doParse(String, Element,
 *      BeanDefinitionRegistry)
 */
protected final void doParse(String cacheProviderFacadeId, Element element, BeanDefinitionRegistry registry) {
    String id = "cacheManager";
    Class clazz = getCacheManagerClass();
    RootBeanDefinition cacheManager = new RootBeanDefinition(clazz);
    MutablePropertyValues cacheManagerProperties = new MutablePropertyValues();
    cacheManager.setPropertyValues(cacheManagerProperties);

    PropertyValue configLocation = parseConfigLocationProperty(element);
    cacheManagerProperties.addPropertyValue(configLocation);
    registry.registerBeanDefinition(id, cacheManager);

    BeanDefinition cacheProviderFacade = registry.getBeanDefinition(cacheProviderFacadeId);
    cacheProviderFacade.getPropertyValues().addPropertyValue("cacheManager", new RuntimeBeanReference(id));
}

From source file:com.tacitknowledge.flip.spring.config.FeatureServiceHandlerParser.java

@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder
            .rootBeanDefinition(FeatureServiceDirectFactory.class);
    RootBeanDefinition factoryBean = (RootBeanDefinition) factoryBuilder.getBeanDefinition();
    parserContext.getRegistry().registerBeanDefinition(FlipSpringAspect.FEATURE_SERVICE_FACTORY_BEAN_NAME,
            factoryBean);/*ww  w .j a va  2 s .com*/

    MutablePropertyValues factoryPropertyValues = new MutablePropertyValues();
    factoryBean.setPropertyValues(factoryPropertyValues);

    String environmentBean = element.getAttribute("environment");
    if (environmentBean != null && !environmentBean.isEmpty()) {
        factoryPropertyValues.addPropertyValue("environment", new RuntimeBeanNameReference(environmentBean));
    }

    Element contextProvidersElement = DomUtils.getChildElementByTagName(element, "context-providers");
    if (contextProvidersElement != null) {
        List contextProvidersList = parserContext.getDelegate().parseListElement(contextProvidersElement,
                factoryBean);
        if (contextProvidersList != null && !contextProvidersList.isEmpty()) {
            factoryPropertyValues.addPropertyValue("contextProviders", contextProvidersList);
        }
    }

    Element propertyReadersElement = DomUtils.getChildElementByTagName(element, "property-readers");
    if (propertyReadersElement != null && propertyReadersElement.hasChildNodes()) {
        List propertyReadersList = parserContext.getDelegate().parseListElement(propertyReadersElement,
                factoryBean);
        if (propertyReadersList != null && !propertyReadersList.isEmpty()) {
            factoryPropertyValues.addPropertyValue("propertyReaders", propertyReadersList);
        }
    }

    Element propertiesElement = DomUtils.getChildElementByTagName(element, "properties");
    if (propertiesElement != null && propertiesElement.hasChildNodes()) {
        Properties properties = parserContext.getDelegate().parsePropsElement(propertiesElement);
        if (properties != null && !properties.isEmpty()) {
            factoryPropertyValues.addPropertyValue("properties", properties);
        }
    }

    BeanDefinitionBuilder featureServiceBuilder = BeanDefinitionBuilder.genericBeanDefinition();
    BeanDefinition featureServiceRawBean = featureServiceBuilder.getRawBeanDefinition();
    featureServiceRawBean.setFactoryBeanName(FlipSpringAspect.FEATURE_SERVICE_FACTORY_BEAN_NAME);
    featureServiceRawBean.setFactoryMethodName("createFeatureService");
    parserContext.getRegistry().registerBeanDefinition(FlipSpringAspect.FEATURE_SERVICE_BEAN_NAME,
            featureServiceBuilder.getBeanDefinition());

    return null;
}

From source file:org.atomserver.utils.test.TestingAtomServer.java

private Server createServer(int port, String atomserverServletContext) {
    // set up the server and the atomserver web application context
    Server server = new Server(port);
    Context context = new Context(server, "/" + atomserverServletContext, true /*sessions*/,
            false /*no security*/);

    // we need to hard-code certain system properties to get the behavior we want here - we
    // will re-set them when we're done
    Properties properties = (Properties) System.getProperties().clone();
    System.setProperty("atomserver.env", "asdev-hsql-mem");
    System.setProperty("atomserver.servlet.context", atomserverServletContext);

    // TODO: this should be removed
    System.setProperty("atomserver.servlet.mapping", "v1");

    // our Spring application context will start off by loading the basic built-in bean
    // definitions
    appContext = new GenericWebApplicationContext();

    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext);
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/propertyConfigurerBeans.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/databaseBeans.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/logBeans.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/storageBeans.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/abderaBeans.xml"));

    // if we were given a Spring config location, we use that -- otherwise we configure the
    // workspaces that were set up through the API
    if (springBeansLocation != null) {
        xmlReader.loadBeanDefinitions(new ClassPathResource(springBeansLocation));
    } else {/*w  w w  . j av a 2  s. c  o m*/
        RootBeanDefinition workspaces = new RootBeanDefinition(HashSet.class);
        ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
        constructorArgumentValues.addGenericArgumentValue(workspaceSet);
        workspaces.setConstructorArgumentValues(constructorArgumentValues);

        appContext.registerBeanDefinition("org.atomserver-workspaces", workspaces);
    }

    // override the base content storage to use DB-based storage
    RootBeanDefinition storage = new RootBeanDefinition(DBBasedContentStorage.class);
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.addPropertyValue("contentDAO", new RuntimeBeanReference("org.atomserver-contentDAO"));
    propertyValues.addPropertyValue("entriesDAO", new RuntimeBeanReference("org.atomserver-entriesDAO"));
    storage.setPropertyValues(propertyValues);
    appContext.registerBeanDefinition("org.atomserver-contentStorage", storage);

    // clear the existing ENV
    ConfigurationAwareClassLoader.invalidateENV();

    // refresh the context to actually instantiate everything.
    appContext.refresh();

    // re-set the system properties
    System.setProperties(properties);

    // clear the update ENV
    ConfigurationAwareClassLoader.invalidateENV();

    // put our app context into the servlet context
    context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext);

    // load and init the service context for v1
    final ServiceContext serviceContext = (ServiceContext) appContext.getBean(ServiceContext.class.getName());
    serviceContext.init(new Abdera(), Collections.EMPTY_MAP);

    // create a new AtomServerServlet - but override the createServiceContext method
    AtomServerServlet servlet = new AtomServerServlet() {
        protected ServiceContext createServiceContext() {
            return serviceContext;
        }
    };

    // load and init the service context for v2
    final ServiceContext serviceContextV2 = (ServiceContext) appContext
            .getBean("org.atomserver-serviceContext.v2");
    serviceContextV2.init(new Abdera(), Collections.EMPTY_MAP);

    // create a new AtomServerServlet - but override the createServiceContext method
    AtomServerServlet servletV2 = new AtomServerServlet() {
        protected ServiceContext createServiceContext() {
            return serviceContextV2;
        }
    };

    // register the servlets
    context.addServlet(new ServletHolder(servlet), "/v1/*");
    context.addServlet(new ServletHolder(servletV2), "/v2/*");

    EntriesDAOiBatisImpl entriesDAO = (EntriesDAOiBatisImpl) appContext.getBean("org.atomserver-entriesDAO");
    entriesDAO.setUseWorkspaceCollectionCache(false);

    // ready to be started
    return server;
}

From source file:org.atomserver.utils.test.TestingAtomServer.java

/**
 * add a new workspace to the testing server with the given name and localization flag.
 *
 * @param name      the name of the workspace
 * @param localized true iff the workspace is localized
 * @return a TestWorkspaceConfigurer to further configure the workspace
 *//*from  www .ja v  a2s.  c  o  m*/
public TestWorkspaceConfigurer addWorkspace(String name, boolean localized) {
    // create a bean definition for the workspace and add it to the managed set.
    final RootBeanDefinition workspace = new RootBeanDefinition(WorkspaceOptions.class);

    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.addPropertyValue("name", name);
    propertyValues.addPropertyValue("defaultLocalized", localized);
    propertyValues.addPropertyValue("defaultProducingEntryCategoriesFeedElement", true);
    propertyValues.addPropertyValue("defaultContentStorage",
            new RuntimeBeanReference("org.atomserver-contentStorage"));
    propertyValues.addPropertyValue("defaultContentValidator",
            new RuntimeBeanReference("org.atomserver-simpleXMLContentValidator"));
    propertyValues.addPropertyValue("defaultCategoriesHandler",
            new RuntimeBeanReference("org.atomserver-entryCategoriesHandler"));
    propertyValues.addPropertyValue("defaultEntryIdGenerator",
            new RuntimeBeanReference("org.atomserver-entryIdGenerator"));

    workspace.setPropertyValues(propertyValues);

    workspaceSet.add(workspace);

    return new TestWorkspaceConfigurer() {
        // if given a RNC location, we spin up a RelaxNGValidator to validate with it
        public TestWorkspaceConfigurer setRncLocation(String rncLocation) {
            RootBeanDefinition autotagger = new RootBeanDefinition(RelaxNGValidator.class);
            MutablePropertyValues propertyValues = new MutablePropertyValues();
            propertyValues.addPropertyValue("schemaLocation", rncLocation);
            autotagger.setPropertyValues(propertyValues);
            workspace.getPropertyValues().addPropertyValue("defaultContentValidator", autotagger);
            return this;
        }

        // if given an XPathAutoTagger script, set up a tagger to use it
        public TestWorkspaceConfigurer setXPathAutotaggerRules(String rules) {
            RootBeanDefinition autotagger = new RootBeanDefinition(XPathAutoTagger.class);
            MutablePropertyValues propertyValues = new MutablePropertyValues();
            propertyValues.addPropertyValue("categoriesHandler",
                    new RuntimeBeanReference("org.atomserver-entryCategoriesHandler"));
            propertyValues.addPropertyValue("script", rules);
            autotagger.setPropertyValues(propertyValues);
            workspace.getPropertyValues().addPropertyValue("defaultAutoTagger", autotagger);
            return this;
        }

        // allow for arbitrary property setting on the workspace bean -- requires knowledge
        // of the Spring bean factory APIs
        public TestWorkspaceConfigurer addPropertyValue(String name, Object value) {
            workspace.getPropertyValues().addPropertyValue(name, value);
            return this;
        }
    };
}

From source file:org.openadaptor.spring.SpringAdaptor.java

/**
 * Configure the default PropertyPlaceholderConfigurer.
 * <br>/*from   w  w w  .  j  av  a 2 s.c  o  m*/
 * Unless suppressAutomaticPropsConfig is set true by supplying -noprops as a command line arg then
 * this method creates and installs a PropertyPlaceholderConfigurer which allows access to System Properties
 * and optionally add all -props defined urls as property resource locations.<br>
 * With one exception all urls are passed through to the context in order to locate the resource. The exception
 * is a url that is not prefixed with a protocol is assumed to be a file and arbitratily prefixed with "file:"<br>
 * NB the arbitrary name given to the generated PropertyPlaceholderConfigurer is "openadaptorAutoGeneratedSystemPropertyConfigurer".
 *
 * @param context Spring Context being used.
 * @param propsUrlList Supplied List or Property URLS.
 */
protected void configureProperties(GenericApplicationContext context, ArrayList propsUrlList) {
    // System properties

    if (!suppressAutomaticPropsConfig) {

        if (isPropertyPlaceholderPresent(context)) {
            log.warn(
                    "Spring configuration file already has PropertyPlaceholderConfigurers defined. Please ensure any conflicts are resolved satisfactorily.");
        }

        MutablePropertyValues systemPropertiesModeProperties = new MutablePropertyValues();
        systemPropertiesModeProperties.addPropertyValue("staticField",
                "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK");

        RootBeanDefinition systemPropertiesMode = new RootBeanDefinition(FieldRetrievingFactoryBean.class);
        systemPropertiesMode.setPropertyValues(systemPropertiesModeProperties);

        MutablePropertyValues properties = new MutablePropertyValues();
        properties.addPropertyValue("ignoreResourceNotFound", "false"); // Will cause an eror if a resource url is bogus
        Iterator propsUrlIter = propsUrlList.iterator();
        ArrayList resourceList = new ArrayList();
        while (propsUrlIter.hasNext()) {
            resourceList.add(context.getResource(ensureProtocol((String) propsUrlIter.next())));
        }
        properties.addPropertyValue("locations", resourceList);
        properties.addPropertyValue("systemPropertiesMode", systemPropertiesMode);
        RootBeanDefinition propertyHolder = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
        propertyHolder.setPropertyValues(properties);

        context.registerBeanDefinition("openadaptorAutoGeneratedSystemPropertyConfigurer", propertyHolder);
    }
}

From source file:org.openadaptor.spring.SpringAdaptor.java

/**
 * Registers an instance of an {@link Adaptor} with the Spring context.
 * <p>//from w w w.j  a  v a2s.  c  o  m
 * Common OpenAdaptor configurations include an {@link Adaptor} with a 
 * {@link Router} which defines an ordered list of {@link IComponent}s. If 
 * no adaptor bean is explicitly registered, this method will auto-configure 
 * and register one.
 * <p>
 * If a {@link Router} is explicitly registered in the Spring context, that
 * will be autowired as the {@link Adaptor}'s <code>messageProcessor</code>.
 * Otherwise, a {@link Router} will be automatically configured and registered.
 * 
 * @param factory the ListableBeanFactory Spring context factory
 * @param id - String containing the id to use for the adaptor
 * @return String containing the id for the Adaptor (
 */

protected String registerAdaptor(ListableBeanFactory factory, String id) {
    String[] ids = factory.getBeanNamesForType(Router.class);
    Router router = null;

    if (ids.length == 1) {
        router = (Router) factory.getBean(ids[0]);
    } else if (ids.length == 0) {
        router = registerRouter(factory);
    }

    MutablePropertyValues properties = new MutablePropertyValues();
    properties.addPropertyValue("messageProcessor", router);
    RootBeanDefinition beanDefinition = new RootBeanDefinition(Adaptor.class);
    beanDefinition.setPropertyValues(properties);
    ((GenericApplicationContext) factory).registerBeanDefinition(id, beanDefinition);
    setBeanId(id);
    return id;
}

From source file:org.openadaptor.spring.SpringAdaptor.java

/**
 * Registers an instance of a {@link Router} with the Spring context. 
 * <p>// w w w.  j a va  2s .co m
 * This method adds all beans registered in the Spring context that are
 * instances of {@link IComponent} to the router's <code>processors</code> 
 * list in <strong>the order in which they are declared in the Spring 
 * configuration</strong>.
 * <p>
 * The only exception is any bean with an id of <code>ExceptionProcessor</code>,
 * which is set as the <code>exceptionProcessor</code> property of the
 * {@link Router}.
 * <p>
 * Note that this means only basic, single pipeline router configurations
 * may be auto-configured in this way. Complex configurations that require
 * a <code>processMap</code> must be defined explicitly. 
 * 
 * @param factory the ListableBeanFactory Spring context factory
 * @return a configured Router
 */
protected Router registerRouter(ListableBeanFactory factory) {
    String[] ids = factory.getBeanNamesForType(IComponent.class);

    if (ids.length == 0) {
        throw new RuntimeException("No Component beans found in config");
    }

    List processors = new ArrayList(ids.length);
    Object exceptionProcessor = null;

    for (int i = 0; i < ids.length; i++) {
        if (!ids[i].equals(DEFAULT_EXCEPTION_PROCESSOR_ID)) {
            processors.add(factory.getBean(ids[i]));
        } else {
            exceptionProcessor = factory.getBean(ids[i]);
        }
    }

    MutablePropertyValues properties = new MutablePropertyValues();
    properties.addPropertyValue("processors", processors);

    if (exceptionProcessor != null) {
        properties.addPropertyValue("exceptionProcessor", exceptionProcessor);
    }

    RootBeanDefinition beanDefinition = new RootBeanDefinition(Router.class);
    beanDefinition.setPropertyValues(properties);
    ((GenericApplicationContext) factory).registerBeanDefinition(DEFAULT_ROUTER_ID, beanDefinition);

    return (Router) factory.getBean(DEFAULT_ROUTER_ID);
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testSelfReference() {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("spouse", new RuntimeBeanReference("self"));
    RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
    bd.setPropertyValues(pvs);
    lbf.registerBeanDefinition("self", bd);
    TestBean self = (TestBean) lbf.getBean("self");
    assertEquals(self, self.getSpouse());
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testPossibleMatches() {
    try {//from w w w.  j  a v  a2  s. c  o  m
        DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.add("ag", "foobar");
        RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
        bd.setPropertyValues(pvs);
        lbf.registerBeanDefinition("tb", bd);
        lbf.getBean("tb");
        fail("Should throw exception on invalid property");
    } catch (BeanCreationException ex) {
        assertTrue(ex.getCause() instanceof NotWritablePropertyException);
        NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause();
        // expected
        assertEquals(1, cause.getPossibleMatches().length);
        assertEquals("age", cause.getPossibleMatches()[0]);
    }
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testCustomEditor() {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
        @Override//from   w w  w.j a va 2  s  .  c  om
        public void registerCustomEditors(PropertyEditorRegistry registry) {
            NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
            registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
        }
    });
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("myFloat", "1,1");
    RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
    bd.setPropertyValues(pvs);
    lbf.registerBeanDefinition("testBean", bd);
    TestBean testBean = (TestBean) lbf.getBean("testBean");
    assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}