Example usage for org.springframework.beans.factory.config PropertyPlaceholderConfigurer PropertyPlaceholderConfigurer

List of usage examples for org.springframework.beans.factory.config PropertyPlaceholderConfigurer PropertyPlaceholderConfigurer

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config PropertyPlaceholderConfigurer PropertyPlaceholderConfigurer.

Prototype

PropertyPlaceholderConfigurer

Source Link

Usage

From source file:co.paralleluniverse.common.spring.SpringContainerHelper.java

public static ConfigurableApplicationContext createContext(String defaultDomain, Resource xmlResource,
        Object properties, BeanFactoryPostProcessor beanFactoryPostProcessor) {
    LOG.info("JAVA: {} {}, {}", new Object[] { System.getProperty("java.runtime.name"),
            System.getProperty("java.runtime.version"), System.getProperty("java.vendor") });
    LOG.info("OS: {} {}, {}", new Object[] { System.getProperty("os.name"), System.getProperty("os.version"),
            System.getProperty("os.arch") });
    LOG.info("DIR: {}", System.getProperty("user.dir"));

    final DefaultListableBeanFactory beanFactory = createBeanFactory();
    final GenericApplicationContext context = new GenericApplicationContext(beanFactory);
    context.registerShutdownHook();/*from   w ww  .ja  va  2  s  .  c  o m*/

    final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer
            .setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);

    if (properties != null) {
        if (properties instanceof Resource)
            propertyPlaceholderConfigurer.setLocation((Resource) properties);
        else if (properties instanceof Properties)
            propertyPlaceholderConfigurer.setProperties((Properties) properties);
        else
            throw new IllegalArgumentException(
                    "Properties argument - " + properties + " - is of an unhandled type");
    }
    context.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);

    // MBean exporter
    //final MBeanExporter mbeanExporter = new AnnotationMBeanExporter();
    //mbeanExporter.setServer(ManagementFactory.getPlatformMBeanServer());
    //beanFactory.registerSingleton("mbeanExporter", mbeanExporter);
    context.registerBeanDefinition("mbeanExporter", getMBeanExporterBeanDefinition(defaultDomain));

    // inject bean names into components
    context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {
                try {
                    final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                    if (beanDefinition.getBeanClassName() != null) { // van be null for factory methods
                        final Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
                        if (Component.class.isAssignableFrom(beanClass))
                            beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, beanName);
                    }
                } catch (Exception ex) {
                    LOG.error("Error loading bean " + beanName + " definition.", ex);
                    throw new Error(ex);
                }
            }
        }
    });

    if (beanFactoryPostProcessor != null)
        context.addBeanFactoryPostProcessor(beanFactoryPostProcessor);

    beanFactory.registerCustomEditor(org.w3c.dom.Element.class,
            co.paralleluniverse.common.util.DOMElementProprtyEditor.class);

    final Map<String, Object> beans = new HashMap<String, Object>();

    beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Loading bean {} [{}]", beanName, bean.getClass().getName());
            beans.put(beanName, bean);

            if (bean instanceof Service) {
                final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                Collection<String> dependencies = getBeanDependencies(beanDefinition);

                for (String dependeeName : dependencies) {
                    Object dependee = beanFactory.getBean(dependeeName);
                    if (dependee instanceof Service) {
                        ((Service) dependee).addDependedBy((Service) bean);
                        ((Service) bean).addDependsOn((Service) dependee);
                    }
                }
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Bean {} [{}] loaded", beanName, bean.getClass().getName());
            return bean;
        }
    });

    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
    xmlReader.loadBeanDefinitions(xmlResource);

    // start container
    context.refresh();

    // Call .postInit() on all Components
    // There's probably a better way to do this
    try {
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            final String beanName = entry.getKey();
            final Object bean = entry.getValue();
            if (bean instanceof Component) {
                LOG.info("Performing post-initialization on bean {} [{}]", beanName, bean.getClass().getName());
                ((Component) bean).postInit();
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    return context;
}

From source file:com.retroduction.carma.application.CarmaDriverSetup.java

public void init() {
    GenericApplicationContext newAppContext = new GenericApplicationContext(this.parentContext);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(newAppContext);

    for (String res : this.beanDefinitionResources) {
        xmlReader.loadBeanDefinitions(res);
    }/* w w  w . j a  v a2  s  .c  o m*/

    PropertyPlaceholderConfigurer customerPropsProcessor = new PropertyPlaceholderConfigurer();
    customerPropsProcessor.setProperties(this.configurationParameters);
    newAppContext.addBeanFactoryPostProcessor(customerPropsProcessor);

    newAppContext.refresh();
    newAppContext.registerShutdownHook();
    this.appContext = newAppContext;
}

From source file:org.iternine.jeppetto.testsupport.TestContext.java

public TestContext(String configurationFilename, String propertiesFilename,
        DatabaseProvider... databaseProviders) {
    XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(new ClassPathResource(configurationFilename));
    xmlBeanFactory.setBeanClassLoader(this.getClass().getClassLoader());

    Properties properties = new Properties();

    try {/* w  w w .j  ava 2 s.  c  o m*/
        properties.load(new ClassPathResource(propertiesFilename).getInputStream());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (databaseProviders != null) {
        for (DatabaseProvider databaseProvider : databaseProviders) {
            properties = databaseProvider.modifyProperties(properties);
        }
    }

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(properties);
    configurer.postProcessBeanFactory(xmlBeanFactory);

    try {
        applicationContext = new GenericApplicationContext(xmlBeanFactory);
        applicationContext.refresh();

        if (databaseProviders != null) {
            for (DatabaseProvider databaseProvider : databaseProviders) {
                databases.add(databaseProvider.getDatabase(properties, applicationContext));
            }
        }
    } catch (RuntimeException e) {
        if (databaseProviders != null) {
            for (DatabaseProvider databaseProvider : databaseProviders) {
                if (databaseProvider instanceof Closeable) {
                    try {
                        ((Closeable) databaseProvider).close();
                    } catch (IOException e1) {
                        // ignore
                    }
                }
            }
        }

        throw e;
    }
}

From source file:com.google.enterprise.connector.filesystem.ConfigTest.java

public void testInstantiation() {
    Properties props = new Properties();
    props.putAll(goodConfig);//from   ww w. j  a va 2 s. c o m
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    // Refer to InstanceInfo.makeConnectorWithSpring
    //(com.google.enterprise.connector.instantiator) for more info on how
    // these files are loaded to instantiate connector.
    reader.loadBeanDefinitions(new ClassPathResource(DEFAULTS_CONFIG_FILE, ConfigTest.class));
    reader.loadBeanDefinitions(new ClassPathResource(INSTANCE_CONFIG_FILE, ConfigTest.class));
    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setProperties(props);
    cfg.postProcessBeanFactory(beanFactory);
    String[] beans = beanFactory.getBeanNamesForType(Connector.class);
    assertEquals(1, beans.length);
    Object obj = beanFactory.getBean(beans[0]);
    assertTrue("Expecting instance of Connector interface but the actual " + "instance: "
            + obj.getClass().toString(), obj instanceof Connector);
}

From source file:com.opengamma.component.factory.AbstractSpringComponentFactory.java

/**
 * Creates the application context.//from   w w  w.j  a va 2 s .c  o  m
 * 
 * @param repo  the component repository, not null
 * @return the Spring application context, not null
 */
protected GenericApplicationContext createApplicationContext(ComponentRepository repo) {
    Resource springFile = getSpringFile();
    try {
        repo.getLogger().logDebug("  Spring file: " + springFile.getURI());
    } catch (Exception ex) {
        // ignore
    }

    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    GenericApplicationContext appContext = new GenericApplicationContext(beanFactory);

    PropertyPlaceholderConfigurer properties = new PropertyPlaceholderConfigurer();
    properties.setLocation(getPropertiesFile());

    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    beanDefinitionReader.setValidating(true);
    beanDefinitionReader.setResourceLoader(appContext);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(appContext));
    beanDefinitionReader.loadBeanDefinitions(springFile);

    appContext.getBeanFactory().registerSingleton("injectedProperties", properties);
    appContext.getBeanFactory().registerSingleton("componentRepository", repo);

    appContext.refresh();
    return appContext;
}

From source file:com.google.enterprise.connector.db.MockDBConnectorFactory.java

/**
 * Creates a database connector./*from   w  w  w .  j  a v  a  2s . c om*/
 *
 * @param config map of configuration values.
 */
/* TODO(jlacey): Extract the Spring instantiation code in CM. */
@Override
public Connector makeConnector(Map<String, String> config) throws RepositoryException {
    // TODO(jlacey): The placeholder values are in the EPPC bean in
    // connectorDefaults.xml, but we're not loading that, and doing so
    // would unravel a ball of string: using setLocation instead of
    // setProperties (since the EPPC bean already has properties),
    // which in turn requires the ByteArrayResource machinery in
    // InstanceInfo or writing the properties to a file.
    Properties props = new Properties();
    for (String configKey : DBConnectorType.CONFIG_KEYS) {
        props.put(configKey, "");
    }
    // Escape MyBatis syntax that looks like a Spring placeholder.
    // See https://jira.springsource.org/browse/SPR-4953
    props.put("docIds", "#{'$'}{docIds}");
    props.putAll(config);

    Resource prototype = new ClassPathResource("config/connectorInstance.xml", MockDBConnectorFactory.class);
    Resource defaults = new ClassPathResource("config/connectorDefaults.xml", MockDBConnectorFactory.class);

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(factory);
    try {
        beanReader.loadBeanDefinitions(prototype);
        beanReader.loadBeanDefinitions(defaults);
    } catch (BeansException e) {
        throw new RepositoryException(e);
    }

    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setProperties(props);
    cfg.postProcessBeanFactory(factory);

    String[] beanList = factory.getBeanNamesForType(DiffingConnector.class);
    Assert.assertEquals(Arrays.asList(beanList).toString(), 1, beanList.length);
    return (Connector) factory.getBean(beanList[0]);
}

From source file:com.mmnaseri.dragonfly.sample.Config.java

@Bean
public PropertyPlaceholderConfigurer placeholderConfigurer() {
    final PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setLocation(new ClassPathResource("db.properties"));
    return configurer;
}

From source file:gov.nih.nci.cagrid.identifiers.service.IdentifiersNAServiceImpl.java

public IdentifiersNAServiceImpl() throws RemoteException {
    super();//ww  w  .j av  a 2  s  .c o m

    try {
        String naConfigurationFile = getConfiguration().getNaConfigurationFile();
        String naProperties = getConfiguration().getNaPropertiesFile();
        FileSystemResource naConfResource = new FileSystemResource(naConfigurationFile);
        FileSystemResource naPropertiesResource = new FileSystemResource(naProperties);

        XmlBeanFactory factory = new XmlBeanFactory(naConfResource);
        PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
        cfg.setLocation(naPropertiesResource);
        cfg.postProcessBeanFactory(factory);

        this.namingAuthority = (MaintainerNamingAuthority) factory.getBean(NA_BEAN_NAME,
                MaintainerNamingAuthority.class);

    } catch (Exception e) {
        String message = "Problem inititializing NamingAuthority while loading configuration:" + e.getMessage();
        LOG.error(message, e);
        throw new RemoteException(message, e);
    }
}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.SpringBeansUtil.java

public void initialize(Properties props) {

    PropertyPlaceholderConfigurer config = new PropertyPlaceholderConfigurer();
    config.setProperties(props);/*from  w ww.j av a2 s .c om*/
    config.postProcessBeanFactory(beanFactory);

    saveProperties(props);
}

From source file:nz.co.senanque.madura.bundle.BundleRootImpl.java

public void init(DefaultListableBeanFactory ownerBeanFactory, Properties properties, ClassLoader cl,
        Map<String, Object> inheritableBeans) {
    m_properties = properties;/*from  ww w.j  ava 2 s .  c  om*/
    m_inheritableBeans = inheritableBeans;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    m_classLoader = cl;
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    String contextPath = properties.getProperty("Bundle-Context", "/bundle-spring.xml");
    m_logger.debug("loading context: {}", contextPath);
    ClassPathResource classPathResource = new ClassPathResource(contextPath, cl);
    xmlReader.loadBeanDefinitions(classPathResource);
    PropertyPlaceholderConfigurer p = new PropertyPlaceholderConfigurer();
    p.setProperties(properties);
    ctx.addBeanFactoryPostProcessor(p);
    if (m_logger.isDebugEnabled()) {
        dumpClassLoader(cl);
    }
    for (Map.Entry<String, Object> entry : inheritableBeans.entrySet()) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(InnerBundleFactory.class);
        beanDefinitionBuilder.addPropertyValue("key", entry.getKey());
        beanDefinitionBuilder.addPropertyValue("object", inheritableBeans.get(entry.getKey()));
        ctx.registerBeanDefinition(entry.getKey(), beanDefinitionBuilder.getBeanDefinition());
    }
    Scope scope = ownerBeanFactory.getRegisteredScope("session");
    if (scope != null) {
        ctx.getBeanFactory().registerScope("session", scope);
    }
    ctx.refresh();
    m_applicationContext = ctx;
    Thread.currentThread().setContextClassLoader(classLoader);
}