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

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

Introduction

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

Prototype

@Override
public void setBeanClassName(@Nullable String beanClassName) 

Source Link

Document

Specify the bean class name of this bean definition.

Usage

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.  jav  a2  s .  co  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:org.jfaster.mango.plugin.spring.MangoDaoScanner.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory;
    for (Class<?> daoClass : findMangoDaoClasses()) {
        GenericBeanDefinition bf = new GenericBeanDefinition();
        bf.setBeanClassName(daoClass.getName());
        MutablePropertyValues pvs = bf.getPropertyValues();
        pvs.addPropertyValue("daoClass", daoClass);
        bf.setBeanClass(factoryBeanClass);
        bf.setPropertyValues(pvs);/*ww  w .ja  v a 2s .  co  m*/
        bf.setLazyInit(false);
        dlbf.registerBeanDefinition(daoClass.getName(), bf);
    }
}

From source file:org.romaz.spring.scripting.ext.ExtScriptBeanDefinitionParser.java

/**
 * Parses the dynamic object element and returns the resulting bean definition.
 * Registers a {@link ScriptFactoryPostProcessor} if needed.
 */// www  . ja  v  a  2  s. c o  m
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    // Resolve the script source.
    String value = resolveScriptSource(element, parserContext.getReaderContext());
    if (value == null) {
        return null;
    }

    // Set up infrastructure.
    LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());

    // Create script factory bean definition.
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClassName(this.scriptFactoryClassName);
    bd.setSource(parserContext.extractSource(element));

    // Determine bean scope.
    String scope = element.getAttribute(SCOPE_ATTRIBUTE);
    if (StringUtils.hasLength(scope)) {
        bd.setScope(scope);
    }

    // Determine autowire mode.
    String autowire = element.getAttribute(AUTOWIRE_ATTRIBUTE);
    int autowireMode = parserContext.getDelegate().getAutowireMode(autowire);
    // Only "byType" and "byName" supported, but maybe other default inherited...
    if (autowireMode == GenericBeanDefinition.AUTOWIRE_AUTODETECT) {
        autowireMode = GenericBeanDefinition.AUTOWIRE_BY_TYPE;
    } else if (autowireMode == GenericBeanDefinition.AUTOWIRE_CONSTRUCTOR) {
        autowireMode = GenericBeanDefinition.AUTOWIRE_NO;
    }
    bd.setAutowireMode(autowireMode);

    // Determine dependency check setting.
    String dependencyCheck = element.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE);
    bd.setDependencyCheck(parserContext.getDelegate().getDependencyCheck(dependencyCheck));

    // Retrieve the defaults for bean definitions within this parser context
    BeanDefinitionDefaults beanDefinitionDefaults = parserContext.getDelegate().getBeanDefinitionDefaults();

    // Determine init method and destroy method.
    String initMethod = element.getAttribute(INIT_METHOD_ATTRIBUTE);
    if (StringUtils.hasLength(initMethod)) {
        bd.setInitMethodName(initMethod);
    } else if (beanDefinitionDefaults.getInitMethodName() != null) {
        bd.setInitMethodName(beanDefinitionDefaults.getInitMethodName());
    }

    String destroyMethod = element.getAttribute(DESTROY_METHOD_ATTRIBUTE);
    if (StringUtils.hasLength(destroyMethod)) {
        bd.setDestroyMethodName(destroyMethod);
    } else if (beanDefinitionDefaults.getDestroyMethodName() != null) {
        bd.setDestroyMethodName(beanDefinitionDefaults.getDestroyMethodName());
    }

    // Attach any refresh metadata.
    String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
    if (StringUtils.hasText(refreshCheckDelay)) {
        bd.setAttribute(ScriptFactoryPostProcessor.REFRESH_CHECK_DELAY_ATTRIBUTE, new Long(refreshCheckDelay));
    }

    // Add constructor arguments.
    ConstructorArgumentValues cav = bd.getConstructorArgumentValues();
    int constructorArgNum = 0;
    cav.addIndexedArgumentValue(constructorArgNum++, value);
    if (element.hasAttribute(SCRIPT_INTERFACES_ATTRIBUTE)) {
        cav.addIndexedArgumentValue(constructorArgNum++, element.getAttribute(SCRIPT_INTERFACES_ATTRIBUTE));
    }
    if (element.hasAttribute(SCRIPT_CONFIG_ATTRIBUTE)) {
        cav.addIndexedArgumentValue(constructorArgNum++,
                new RuntimeBeanReference(element.getAttribute(SCRIPT_CONFIG_ATTRIBUTE)));
    }
    // Add any property definitions that need adding.
    parserContext.getDelegate().parsePropertyElements(element, bd);

    return bd;
}

From source file:com.rvantwisk.cnctools.ScreensConfiguration.java

/**
 * Add's a new bean to Spring's context/*from  www .  j ava  2  s  . co m*/
 *
 * @param name
 */
public void registerBean(final String name) {
    if (registeredbeans.containsKey(name)) {
        return;
    }
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClassName(name);
    beanDefinition.setAutowireCandidate(true);
    AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
    registry.registerBeanDefinition(name, beanDefinition);
    factory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    registeredbeans.put(name, Boolean.TRUE);
}

From source file:com.github.steveash.spring.WiringFactoryBeanFactoryPostProcessor.java

private void addPrototypeDef(ConfigurableListableBeanFactory beanFactory, String beanDefName,
        Class<?> protoBeanClass) {
    String beanName = getPrototypeBeanNameFromBeanClass(protoBeanClass);
    if (beanFactory.containsBeanDefinition(beanName)) {
        throw new BeanDefinitionValidationException("Trying to register a bean definition for a synthetic "
                + "prototype bean with name " + beanName + " due to the bean factory of name " + beanDefName
                + " but a bean with this name already exists!");
    }//from  w  w w  .  j av  a 2 s .  c  o  m

    GenericBeanDefinition protoBean = new GenericBeanDefinition();
    protoBean.setLazyInit(true);
    protoBean.setBeanClass(protoBeanClass);
    protoBean.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    protoBean.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    protoBean.setBeanClassName(protoBeanClass.getName());

    log.debug("Dynamically adding prototype bean {} from factory {}", beanName, beanDefName);
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    registry.registerBeanDefinition(beanName, protoBean);
}

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

/**
 * @param parserContext//  www. j a  v  a 2  s .  c  o m
 * @param serviceName TODO
 * @param serviceInterface TODO
 */
private void registerCacheWebService(BeanDefinitionRegistry beanDefinitionRegistry, String beanName,
        String serviceName, String serviceInterface, boolean isOneWay) {
    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClassName("com.dianping.dpsf.spring.ProxyBeanFactory");
    definition.setLazyInit(true);
    definition.setInitMethodName("init");
    MutablePropertyValues propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("serviceName", serviceName);
    propertyValues.addPropertyValue("iface", serviceInterface);
    propertyValues.addPropertyValue("serialize", "hessian");
    propertyValues.addPropertyValue("callMethod", isOneWay ? "oneway" : "sync");
    propertyValues.addPropertyValue("timeout", "10000");
    propertyValues.addPropertyValue("hosts", getRemoteService());
    BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(definition, beanName),
            beanDefinitionRegistry);
}

From source file:org.iff.infra.util.spring.script.ScriptFactoryPostProcessor.java

/**
 * Create a ScriptFactory bean definition based on the given script definition,
 * extracting only the definition data that is relevant for the ScriptFactory
 * (that is, only bean class and constructor arguments).
 * @param bd the full script bean definition
 * @return the extracted ScriptFactory bean definition
 * @see org.springframework.scripting.ScriptFactory
 *///  w  w  w .  j  a  va2s .c  o  m
protected BeanDefinition createScriptFactoryBeanDefinition(BeanDefinition bd) {
    GenericBeanDefinition scriptBd = new GenericBeanDefinition();
    scriptBd.setBeanClassName(bd.getBeanClassName());
    scriptBd.getConstructorArgumentValues().addArgumentValues(bd.getConstructorArgumentValues());
    return scriptBd;
}

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

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;/*from www. j  a va 2s. com*/

    // 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:org.springframework.context.expression.ApplicationContextExpressionTests.java

@Test
public void genericApplicationContext() throws Exception {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    ac.getBeanFactory().registerScope("myScope", new Scope() {
        @Override/* www . j ava2s  . co m*/
        public Object get(String name, ObjectFactory<?> objectFactory) {
            return objectFactory.getObject();
        }

        @Override
        public Object remove(String name) {
            return null;
        }

        @Override
        public void registerDestructionCallback(String name, Runnable callback) {
        }

        @Override
        public Object resolveContextualObject(String key) {
            if (key.equals("mySpecialAttr")) {
                return "42";
            } else {
                return null;
            }
        }

        @Override
        public String getConversationId() {
            return null;
        }
    });

    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    Properties placeholders = new Properties();
    placeholders.setProperty("code", "123");
    ppc.setProperties(placeholders);
    ac.addBeanFactoryPostProcessor(ppc);

    GenericBeanDefinition bd0 = new GenericBeanDefinition();
    bd0.setBeanClass(TestBean.class);
    bd0.getPropertyValues().add("name", "myName");
    bd0.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "original"));
    ac.registerBeanDefinition("tb0", bd0);

    GenericBeanDefinition bd1 = new GenericBeanDefinition();
    bd1.setBeanClassName("#{tb0.class}");
    bd1.setScope("myScope");
    bd1.getConstructorArgumentValues().addGenericArgumentValue("XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ");
    bd1.getConstructorArgumentValues().addGenericArgumentValue("#{mySpecialAttr}");
    ac.registerBeanDefinition("tb1", bd1);

    GenericBeanDefinition bd2 = new GenericBeanDefinition();
    bd2.setBeanClassName("#{tb1.class.name}");
    bd2.setScope("myScope");
    bd2.getPropertyValues().add("name", "{ XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ }");
    bd2.getPropertyValues().add("age", "#{mySpecialAttr}");
    bd2.getPropertyValues().add("country", "${code} #{systemProperties.country}");
    ac.registerBeanDefinition("tb2", bd2);

    GenericBeanDefinition bd3 = new GenericBeanDefinition();
    bd3.setBeanClass(ValueTestBean.class);
    bd3.setScope("myScope");
    ac.registerBeanDefinition("tb3", bd3);

    GenericBeanDefinition bd4 = new GenericBeanDefinition();
    bd4.setBeanClass(ConstructorValueTestBean.class);
    bd4.setScope("myScope");
    ac.registerBeanDefinition("tb4", bd4);

    GenericBeanDefinition bd5 = new GenericBeanDefinition();
    bd5.setBeanClass(MethodValueTestBean.class);
    bd5.setScope("myScope");
    ac.registerBeanDefinition("tb5", bd5);

    GenericBeanDefinition bd6 = new GenericBeanDefinition();
    bd6.setBeanClass(PropertyValueTestBean.class);
    bd6.setScope("myScope");
    ac.registerBeanDefinition("tb6", bd6);

    System.getProperties().put("country", "UK");
    try {
        ac.refresh();

        TestBean tb0 = ac.getBean("tb0", TestBean.class);

        TestBean tb1 = ac.getBean("tb1", TestBean.class);
        assertEquals("XXXmyNameYYY42ZZZ", tb1.getName());
        assertEquals(42, tb1.getAge());

        TestBean tb2 = ac.getBean("tb2", TestBean.class);
        assertEquals("{ XXXmyNameYYY42ZZZ }", tb2.getName());
        assertEquals(42, tb2.getAge());
        assertEquals("123 UK", tb2.getCountry());

        ValueTestBean tb3 = ac.getBean("tb3", ValueTestBean.class);
        assertEquals("XXXmyNameYYY42ZZZ", tb3.name);
        assertEquals(42, tb3.age);
        assertEquals(42, tb3.ageFactory.getObject().intValue());
        assertEquals("123 UK", tb3.country);
        assertEquals("123 UK", tb3.countryFactory.getObject());
        System.getProperties().put("country", "US");
        assertEquals("123 UK", tb3.country);
        assertEquals("123 US", tb3.countryFactory.getObject());
        System.getProperties().put("country", "UK");
        assertEquals("123 UK", tb3.country);
        assertEquals("123 UK", tb3.countryFactory.getObject());
        assertSame(tb0, tb3.tb);

        tb3 = (ValueTestBean) SerializationTestUtils.serializeAndDeserialize(tb3);
        assertEquals("123 UK", tb3.countryFactory.getObject());

        ConstructorValueTestBean tb4 = ac.getBean("tb4", ConstructorValueTestBean.class);
        assertEquals("XXXmyNameYYY42ZZZ", tb4.name);
        assertEquals(42, tb4.age);
        assertEquals("123 UK", tb4.country);
        assertSame(tb0, tb4.tb);

        MethodValueTestBean tb5 = ac.getBean("tb5", MethodValueTestBean.class);
        assertEquals("XXXmyNameYYY42ZZZ", tb5.name);
        assertEquals(42, tb5.age);
        assertEquals("123 UK", tb5.country);
        assertSame(tb0, tb5.tb);

        PropertyValueTestBean tb6 = ac.getBean("tb6", PropertyValueTestBean.class);
        assertEquals("XXXmyNameYYY42ZZZ", tb6.name);
        assertEquals(42, tb6.age);
        assertEquals("123 UK", tb6.country);
        assertSame(tb0, tb6.tb);
    } finally {
        System.getProperties().remove("country");
    }
}