Example usage for org.springframework.beans.factory FactoryBean getObject

List of usage examples for org.springframework.beans.factory FactoryBean getObject

Introduction

In this page you can find the example usage for org.springframework.beans.factory FactoryBean getObject.

Prototype

@Nullable
T getObject() throws Exception;

Source Link

Document

Return an instance (possibly shared or independent) of the object managed by this factory.

Usage

From source file:com.stoxa.SpringXML.TestClass.TestClass.java

public static void main(String[] args) throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("config2.xml");
    FactoryBean factory = context.getBean("contactFactory", ContactBeanFactory.class);

    Contact c1 = (Contact) factory.getObject();
    Contact c2 = (Contact) factory.getObject();
    Contact c3 = (Contact) factory.getObject();
    Contact c4 = (Contact) factory.getObject();
    Contact c5 = (Contact) factory.getObject();

    ContactService contactService = context.getBean("ContactService", ContactService.class);

    System.out.println("ADD CONTACT ==============");
    contactService.addContact(c1);/*from  w ww .j  av a2  s  . c  o m*/
    contactService.addContact(c2);
    contactService.addContact(c3);
    contactService.addContact(c4);
    contactService.addContact(c5);
    List<Contact> result1 = contactService.getAllContacts();
    for (Contact c : result1) {
        System.out.println(c);
    }
    System.out.println("******************************************");

    System.out.println("UPDATE CONTACT ==============");
    Contact change = new Contact("??", "", "+380955019248", "sokolov@yandex.ru");
    contactService.updateContact(change);
    List<Contact> result2 = contactService.getAllContacts();
    for (Contact c : result2) {
        System.out.println(c);
    }
    System.out.println("******************************************");

    System.out.println("DELETE CONTACT ==============");
    contactService.deleteContact(c3);
    List<Contact> result3 = contactService.getAllContacts();
    for (Contact c : result3) {
        System.out.println(c);
    }
    System.out.println("******************************************");

    System.out.println("GET CONTACT ==============");
    Contact contact = contactService.getContact("+380674560901");
    System.out.println(contact);

    System.out.println("******************************************");

    System.out.println("CLEAR ALL CONTACTS ==============");
    contactService.clearAll();
    List<Contact> result4 = contactService.getAllContacts();
    for (Contact c : result4) {
        System.out.println(c);
    }
}

From source file:org.intalio.tempo.workflow.ServiceObjectSupplier.java

public Object getServiceObject(AxisService service) throws AxisFault {
    Parameter fac = service.getParameter("SpringBeanFactory");
    if (fac != null) {
        Thread thread = Thread.currentThread();
        ClassLoader oldClassLoader = thread.getContextClassLoader();
        try {//from w  ww  .  j  a v a 2  s.c  om
            thread.setContextClassLoader(SpringInit.CONTEXT.getClass().getClassLoader());
            String factoryName = (String) fac.getValue();
            LOG.info("Using factory:" + factoryName);
            Object o = SpringInit.CONTEXT.getBean(factoryName);
            //LOG.info("Class:"+o.getClass().getName());
            FactoryBean factory = (FactoryBean) o;
            return factory.getObject();
        } catch (Exception e) {
            LOG.info("Error while using factory", e);
        } finally {
            thread.setContextClassLoader(oldClassLoader);
        }
    }

    String beanName = "#unspecified#";
    Parameter p = service.getParameter("SpringBeanName");
    if (p != null) {
        beanName = (String) p.getValue();
    }
    Object bean = SpringInit.CONTEXT.getBean(beanName);
    if (bean == null) {
        LOG.error("Bean not found: " + beanName);
    }
    return bean;
}

From source file:com.hp.autonomy.frontend.find.core.beanconfiguration.ConfigFileConfiguration.java

@Bean
public TextEncryptor textEncryptor() {
    final FactoryBean<String> passwordFactory = new TextEncryptorPasswordFactory();

    final BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();

    try {/*from w w w  .  j a  v a 2s . com*/
        basicTextEncryptor.setPassword(passwordFactory.getObject());
    } catch (final Exception e) {
        throw new BeanInitializationException("Failed to initialize TextEncryptor for some reason", e);
    }

    return basicTextEncryptor;
}

From source file:com.otterca.common.crypto.X509CertificateBuilderFactoryTest.java

/**
 * Test factory bean./* w  w  w  .  j a  va  2  s. co m*/
 * 
 * @throws Exception
 */
@Test
public void testFactory() throws Exception {
    FactoryBean<X509CertificateBuilder> factory = new X509CertificateBuilderFactory();

    assertEquals(factory.getObjectType(), X509CertificateBuilder.class);
    assertFalse(factory.isSingleton());

    Object obj = factory.getObject();
    assertTrue(obj instanceof X509CertificateBuilder);
}

From source file:org.okj.commons.annotations.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(//ww  w. ja v  a2  s .com
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:org.apache.james.container.spring.lifecycle.osgi.AbstractOSGIAnnotationBeanPostProcessor.java

@Override
@SuppressWarnings("rawtypes")
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        A s = hasAnnotatedProperty(pd);/*from  w w  w.  ja  v  a2s.c om*/
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:org.springframework.batch.core.step.item.FaultTolerantStepFactoryBeanTests.java

private SkipPolicy getSkipPolicy(FactoryBean<Step> factory) throws Exception {
    Object step = factory.getObject();
    Object tasklet = ReflectionTestUtils.getField(step, "tasklet");
    Object chunkProvider = ReflectionTestUtils.getField(tasklet, "chunkProvider");
    return (SkipPolicy) ReflectionTestUtils.getField(chunkProvider, "skipPolicy");
}

From source file:org.springframework.beans.factory.support.AbstractBeanFactory.java

/**
 * Get the object for the given shared bean, either the bean
 * instance itself or its created object in case of a FactoryBean.
 * @param name name that may include factory dereference prefix
 * @param beanInstance the shared bean instance
 * @return the singleton instance of the bean
 *//*from   w w w . jav  a  2 s . co m*/
protected Object getObjectForSharedInstance(String name, Object beanInstance) throws BeansException {
    String beanName = transformedBeanName(name);

    // Don't let calling code try to dereference the
    // bean factory if the bean isn't a factory.
    if (isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
        throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
    }

    // Now we have the bean instance, which may be a normal bean or a FactoryBean.
    // If it's a FactoryBean, we use it to create a bean instance, unless the
    // caller actually wants a reference to the factory.
    if (beanInstance instanceof FactoryBean) {
        if (!isFactoryDereference(name)) {
            // Return bean instance from factory.
            FactoryBean factory = (FactoryBean) beanInstance;
            if (logger.isDebugEnabled()) {
                logger.debug("Bean with name '" + beanName + "' is a factory bean");
            }
            try {
                beanInstance = factory.getObject();
            } catch (Exception ex) {
                throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
            }
            if (beanInstance == null) {
                throw new FactoryBeanNotInitializedException(beanName, "FactoryBean returned null object: "
                        + "probably not fully initialized (maybe due to circular bean reference)");
            }
        } else {
            // The user wants the factory itself.
            if (logger.isDebugEnabled()) {
                logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");
            }
        }
    }

    return beanInstance;
}

From source file:org.springframework.osgi.extensions.annotation.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(/*from   w  ww .j av a2 s.c  o  m*/
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run
                // in stageTwo(). This check means that
                // the call to getObject() will not fail with
                // ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will
                // ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setAvailability(importer, Availability.OPTIONAL);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}