Example usage for org.springframework.beans.factory.support GenericBeanDefinition GenericBeanDefinition

List of usage examples for org.springframework.beans.factory.support GenericBeanDefinition GenericBeanDefinition

Introduction

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

Prototype

public GenericBeanDefinition() 

Source Link

Document

Create a new GenericBeanDefinition, to be configured through its bean properties and configuration methods.

Usage

From source file:guru.qas.martini.annotation.StepsAnnotationProcessorTest.java

@Test(expectedExceptions = FatalBeanException.class)
public void testNonSingletonSteps() {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("emptyContext.xml");
    ConfigurableListableBeanFactory factory = context.getBeanFactory();

    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(DuplicateGivenBeanA.class);
    definition.setLazyInit(false);/*from   w ww  . j av a  2s .  co m*/
    definition.setScope("prototype");

    BeanDefinitionRegistry registry = BeanDefinitionRegistry.class.cast(factory);
    registry.registerBeanDefinition(DuplicateGivenBeanA.class.getName(), definition);
    process(context, new DuplicateGivenBeanA());
}

From source file:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//from  www. j a v  a 2  s  . c o  m

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurerTest.java

@Test
public void testProcessPropertiesWithAnnotatedGetter() {
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(AnnotatedGetterTestBean.class);
    beanFactory.registerBeanDefinition(TEST_BEAN_NAME, beanDefinition);

    properties.put(TEST_KEY, TEST_VALUE);

    configurer.processProperties(beanFactory, properties);

    assertNotNull(/*from   www . ja  v a2s . c  om*/
            beanFactory.getBeanDefinition(TEST_BEAN_NAME).getPropertyValues().getPropertyValue("property"));
    assertEquals(TEST_VALUE, beanFactory.getBeanDefinition(TEST_BEAN_NAME).getPropertyValues()
            .getPropertyValue("property").getValue());
}

From source file:org.mybatis.spring.config.NamespaceTest.java

private GenericApplicationContext setupSqlSessionTemplate() {

    GenericApplicationContext genericApplicationContext = setupSqlSessionFactory();
    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionTemplate.class);
    ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
    constructorArgs.addGenericArgumentValue(new RuntimeBeanReference("sqlSessionFactory"));
    definition.setConstructorArgumentValues(constructorArgs);
    genericApplicationContext.registerBeanDefinition("sqlSessionTemplate", definition);
    return genericApplicationContext;
}

From source file:org.mybatis.spring.mapper.MapperScannerConfigurerTest.java

@Test
public void testScanWithExplicitSqlSessionTemplate() throws Exception {
    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(SqlSessionTemplate.class);
    ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
    constructorArgs.addGenericArgumentValue(new RuntimeBeanReference("sqlSessionFactory"));
    definition.setConstructorArgumentValues(constructorArgs);
    applicationContext.registerBeanDefinition("sqlSessionTemplate", definition);

    applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add("sqlSessionTemplateBeanName",
            "sqlSessionTemplate");

    testInterfaceScan();//  w w w . j  ava  2 s  . c  om
}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurerTest.java

@Test
public void testProcessPropertiesWithAnnotatedFieldNoSetter() {
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(NoSetterTestBean.class);
    beanFactory.registerBeanDefinition(TEST_BEAN_NAME, beanDefinition);

    properties.put(TEST_KEY, TEST_VALUE);

    try {//w  w w . j  a va  2s  .  c o m
        configurer.processProperties(beanFactory, properties);
    } catch (BeanConfigurationException e) {
        return;
    }

    fail("Should throw BeanConfigurationException on no property setter.");
}

From source file:com.dianping.avatar.cache.spring.CacheBeanDefinitionParser.java

/**
 * Register jms listener definition/*w w  w. j  av a 2  s. c om*/
 */
private void registerJmsDefinition(Element element, ParserContext parserContext) {
    GenericBeanDefinition definition = new GenericBeanDefinition();
    MutablePropertyValues propertyValues = definition.getPropertyValues();

    definition = new GenericBeanDefinition();
    definition.setBeanClass(CacheKeyTypeVersionUpdateListener.class);
    propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("cacheItemConfigManager", new RuntimeBeanReference(cacheItemConfigManager));
    BeanDefinitionReaderUtils.registerBeanDefinition(
            new BeanDefinitionHolder(definition, "keyTypeVersionUpdateListener"), parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    definition.setBeanClass(SingleCacheRemoveListener.class);
    propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("cacheClientFactory",
            new RuntimeBeanReference(DEFAULT_CACHE_CLIENT_FACTORY_ID));
    BeanDefinitionReaderUtils.registerBeanDefinition(
            new BeanDefinitionHolder(definition, "singleCacheRemoveListener"), parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    definition.setBeanClass(CacheConfigurationUpdateListener.class);
    propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("cacheClientFactory",
            new RuntimeBeanReference(DEFAULT_CACHE_CLIENT_FACTORY_ID));
    BeanDefinitionReaderUtils.registerBeanDefinition(
            new BeanDefinitionHolder(definition, "cacheConfigUpdateListener"), parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    definition.setBeanClass(CacheKeyConfigUpdateListener.class);
    propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("cacheItemConfigManager", new RuntimeBeanReference(cacheItemConfigManager));
    BeanDefinitionReaderUtils.registerBeanDefinition(
            new BeanDefinitionHolder(definition, "cacheKeyConfigUpdateListener"), parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    definition.setBeanClass(MessageReceiver.class);
    propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("mappingList[0]", new RuntimeBeanReference("keyTypeVersionUpdateListener"));
    propertyValues.addPropertyValue("mappingList[1]", new RuntimeBeanReference("singleCacheRemoveListener"));
    propertyValues.addPropertyValue("mappingList[2]", new RuntimeBeanReference("cacheConfigUpdateListener"));
    propertyValues.addPropertyValue("mappingList[3]", new RuntimeBeanReference("cacheKeyConfigUpdateListener"));
    BeanDefinitionReaderUtils.registerBeanDefinition(
            new BeanDefinitionHolder(definition, "dispatchMessageListener"), parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    definition.setBeanClass(MongoMQService.class);
    ConstructorArgumentValues constructorArgumentValues = definition.getConstructorArgumentValues();
    constructorArgumentValues.addGenericArgumentValue("${avatar-cache.swallow.url}", "java.lang.String");
    BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(definition, "MQService"),
            parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    definition.setBeanClass(Destination.class);
    definition.setFactoryMethodName(DEFAULT_CACHE_JMS_MODE);
    constructorArgumentValues = definition.getConstructorArgumentValues();
    constructorArgumentValues.addGenericArgumentValue(DEFAULT_CACHE_JMS_TOPIC_NAME, "java.lang.String");
    BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(definition, "CacheDestination"),
            parserContext.getRegistry());

    definition = new GenericBeanDefinition();
    //        definition.setBeanClass(MongoMessageConsumer.class);
    definition.setFactoryBeanName("MQService");
    definition.setFactoryMethodName("createConsumer");
    constructorArgumentValues = definition.getConstructorArgumentValues();
    //TODO where to get the DEFAULT_CACHE_JMS_TOPIC_NAME
    constructorArgumentValues.addGenericArgumentValue(new RuntimeBeanReference("CacheDestination"));
    propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("messageListener", new RuntimeBeanReference("dispatchMessageListener"));
    BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(definition, "cacheConsumer"),
            parserContext.getRegistry());
}

From source file:com.longio.spring.LioBootstrap.java

private void bootEndpoints(DefaultListableBeanFactory bf, String name) {
    RootBeanDefinition bd = (RootBeanDefinition) bf.getBeanDefinition(name);
    String fbMethod = bd.getFactoryMethodName();
    String fbName = bd.getFactoryBeanName();
    Object fb = bf.getBean(fbName);

    if (!bf.containsBeanDefinition("longio.connector")) {
        GenericBeanDefinition bdd = new GenericBeanDefinition();
        bdd.setBeanClass(NettyConnector.class);
        bf.registerBeanDefinition("longio.connector", bdd);
    }/*  w w w  .  ja v a2 s .c o  m*/

    Connector connector = bf.getBean("longio.connector", Connector.class);

    Class<?> fbCls = fb.getClass().getSuperclass();
    Method m;
    try {
        m = fbCls.getDeclaredMethod(fbMethod);
        Boots boots = m.getAnnotation(Boots.class);
        if (boots == null) {
            MethodDispatcher dispatcher = new MethodDispatcher();
            Boot b = m.getAnnotation(Boot.class);
            connector.start(b.port(), dispatcher, b.tt(), b.pt(), b.pkg());
            logger.info("connector start at port [" + b.port() + "] with tt = " + b.tt() + " and pt = " + b.pt()
                    + " for pkg = " + b.pkg());
        } else {
            for (Boot b : boots.value()) {
                MethodDispatcher dispatcher = new MethodDispatcher();
                connector.start(b.port(), dispatcher, b.tt(), b.pt(), b.pkg());
                logger.info("connector start at port [" + b.port() + "] with tt = " + b.tt() + " and pt = "
                        + b.pt() + " for pkg = " + b.pkg());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.kurento.kmf.spring.KurentoApplicationContextUtils.java

public static AnnotationConfigApplicationContext createKurentoHandlerServletApplicationContext(
        Class<?> servletClass, String servletName, ServletContext sc, String handlerClassName) {
    Assert.notNull(sc, "Cannot create Kurento ServletApplicationContext from null ServletContext");
    Assert.notNull(servletClass, "Cannot create KurentoServletApplicationContext from a null Servlet class");
    Assert.notNull(servletClass, "Cannot create KurentoServletApplicationContext from a null Hanlder class");

    if (childContexts == null) {
        childContexts = new ConcurrentHashMap<String, AnnotationConfigApplicationContext>();
    }/*from  w  w w.  j a v  a 2s .c  o m*/

    AnnotationConfigApplicationContext childContext = childContexts
            .get(servletClass.getName() + ":" + servletName);
    Assert.isNull(childContext, "Pre-existing context found associated to servlet class "
            + servletClass.getName() + " and servlet name " + servletName);

    childContext = new AnnotationConfigApplicationContext();
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClassName(handlerClassName);
    childContext.registerBeanDefinition(handlerClassName, beanDefinition);
    if (!kurentoApplicationContextExists()) {
        createKurentoApplicationContext(sc);
    }
    childContext.setParent(getKurentoApplicationContext());
    childContext.refresh();
    childContexts.put(servletClass.getName(), childContext);

    return childContext;
}

From source file:com.capgemini.boot.core.factory.internal.SettingBackedBeanFactoryPostProcessor.java

private BeanDefinition createBeanDefinition(Object settings, Object setting, String factoryBeanName,
        Method factoryMethod) {//from  w ww.j a v a2  s.c  o  m
    final GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setFactoryBeanName(factoryBeanName);
    definition.setFactoryMethodName(factoryMethod.getName());

    //Create method arguments (confusingly called constructor arguments in spring)
    final ConstructorArgumentValues arguments = new ConstructorArgumentValues();
    arguments.addIndexedArgumentValue(0, setting);

    final int parameterCount = factoryMethod.getParameterTypes().length;
    if (parameterCount == 2) {
        arguments.addIndexedArgumentValue(1, settings);
    } else if (parameterCount > 2) {
        throw getExceptionFactory().createInvalidArgumentsException(factoryMethod);
    }

    //TODO more checking of method arguments to ensure they're correct

    definition.setConstructorArgumentValues(arguments);

    return definition;
}