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

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

Introduction

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

Prototype

public void setProperties(Properties properties) 

Source Link

Document

Set local properties, e.g.

Usage

From source file:com.zekke.webapp.config.TestConfig.java

@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(ResourceLoader resourceLoader)
        throws IOException {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ppc.setProperties(configProperties(resourceLoader).getObject());
    return ppc;/*from w  w  w .j  a  v a  2  s  .c  om*/
}

From source file:com.zekke.webapp.config.MainConfig.java

/**
 * Creates a new PropertyPlaceholderConfigurer.
 *
 * @param resourceLoader any ResourceLoader.
 * @return a PropertyPlaceholderConfigurer.
 * @throws IOException if the properties file is not found in
 * {@link #CONFIG_PROPERTIES_URI}.//from w ww . j a  v a  2  s. c  o  m
 */
@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(ResourceLoader resourceLoader)
        throws IOException {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ppc.setProperties(configProperties(resourceLoader).getObject());
    return ppc;
}

From source file:ch.tatool.app.util.ContextUtils.java

/**
 * Create a new BeanFactory using the main ApplicationContext as parent.
 * /*from   ww  w.  jav a  2s . c o m*/
 * @param classpath the path to the bean definition file in the classpath 
 * @param properties set of properties that should be replaced in the definitions
 * @return a BeanFactory instance
 */
public static BeanFactory createBeanFactory(String classpath, Properties properties) {
    // create an empty bean factory 
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

    // load the context file - has to be done here, otherwise properties won't get resolved
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    Resource resource = new ClassPathResource(classpath);
    reader.loadBeanDefinitions(resource);

    // apply the properties to the context
    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(properties);
    configurer.setIgnoreUnresolvablePlaceholders(false);
    configurer.setIgnoreResourceNotFound(false);
    configurer.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK);
    configurer.postProcessBeanFactory(beanFactory);

    return beanFactory;
}

From source file:il.ac.tau.yoavram.pes.SpringRunner.java

public static void run(String[] args) throws IOException {
    System.out.println("Starting " + SpringRunner.class.getSimpleName());
    SimulationConfigurer configurer = new SimulationConfigurer(args);
    if (configurer.getSpringXmlConfig() == null) {
        System.err.println("Spring XML config file not defined");
        System.err.println();//ww w.j  a  va2s .co m
        System.exit(1);
    }
    if (configurer.getProperties() == null) {
        System.err.println("Properties not defined");
        System.err.println();
        System.exit(1);
    }

    // get the properties
    Properties properties = configurer.getProperties();
    String jobName = properties.getProperty(SimulationConfigurer.JOB_NAME_KEY);

    // create context
    AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext();

    // add properties to context
    logger.info("Adding properties to context: " + properties.toString());
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer.setProperties(properties);
    context.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);

    // set config location
    String configLocation = configurer.getSpringXmlConfig().toString();
    logger.info("Loading context from file " + configLocation);
    context.setConfigLocation(configLocation);

    // make sure destroy methods will be called and refresh the context
    context.registerShutdownHook();
    context.refresh();

    // persist properties
    try {
        PropertiesPersister persister = context.getBean(PropertiesPersister.class);
        if (persister != null) {
            persister.persist(properties);
        }
    } catch (NoSuchBeanDefinitionException e) {
        // nothing to do
    }

    // get the simulation bean and run it
    Simulation simulation = context.getBean("simulation", Simulation.class);

    logger.debug("Starting simulation " + jobName);
    simulation.start();
}

From source file:org.pmedv.core.util.ResourceUtils.java

/**
 * Configures a factory from a properties file read from an input stream
 * /*from ww  w .  j a  va2  s.c o m*/
 * @param is       the stream to read the properties from 
 * @param factory  the factory to configure
 */
public static Properties configureFactoryFromInputStream(InputStream is, XmlBeanFactory factory) {

    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

    Properties p = new Properties();

    try {
        p.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    cfg.setProperties(p);
    cfg.postProcessBeanFactory(factory);

    return p;
}

From source file:com.logsniffer.app.CoreAppConfig.java

/**
 * Returns a general properties placeholder configurer based on
 * {@link #logSnifferProperties()}.// w w w .  j  a  v  a2s  . c  o  m
 * 
 * @param props
 *            autowired logSnifferProperties bean
 * @return A general properties placeholder configurer.
 * @throws IOException
 */
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Autowired
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(
        @Qualifier(BEAN_LOGSNIFFER_PROPS) final Properties props) throws IOException {
    final PropertyPlaceholderConfigurer c = new PropertyPlaceholderConfigurer();
    c.setIgnoreResourceNotFound(true);
    c.setIgnoreUnresolvablePlaceholders(true);
    c.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
    c.setProperties(props);
    return c;
}

From source file:org.trustedanalytics.platformcontext.unit.TestConfiguration.java

@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {

    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ppc.setIgnoreResourceNotFound(true);
    final Properties properties = new Properties();
    properties.setProperty("cf.resource", ApiControllerTest.CF_RESOURCE);
    properties.setProperty("cf.cli.version", "");
    properties.setProperty("cf.cli.url", "");
    properties.setProperty("platform.version", "0.1");
    properties.setProperty("platform.coreorg", "coreOrg");
    ppc.setProperties(properties);

    return ppc;/*from   ww  w .j  a v a  2  s.  c  om*/
}

From source file:edu.berkeley.compbio.ncbitaxonomy.service.NcbiTaxonomyServicesContextFactory.java

public static ApplicationContext makeNcbiTaxonomyServicesContext() throws IOException {

    File propsFile = PropertiesUtils.findPropertiesFile("NCBI_TAXONOMY_SERVICE_PROPERTIES", ".ncbitaxonomy",
            "service.properties");

    logger.debug("Using properties file: " + propsFile);
    Properties p = new Properties();
    FileInputStream is = null;//from   w ww.  ja  va  2s .  c  o m
    try {
        is = new FileInputStream(propsFile);
        p.load(is);
    } finally {
        is.close();
    }
    String dbName = (String) p.get("default");

    Map<String, Properties> databases = PropertiesUtils.splitPeriodDelimitedProperties(p);

    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("ncbitaxonomyclient.xml"));

    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    Properties properties = databases.get(dbName);

    if (properties == null) {
        logger.error("Service definition not found: " + dbName);
        logger.error("Valid names: " + StringUtils.join(databases.keySet().iterator(), ", "));
        throw new NcbiTaxonomyRuntimeException("Database definition not found: " + dbName);
    }

    cfg.setProperties(properties);
    ctx.addBeanFactoryPostProcessor(cfg);

    ctx.refresh();

    // add a shutdown hook for the above context...
    ctx.registerShutdownHook();

    return ctx;
}

From source file:org.rivetlogic.utils.IntegrationUtils.java

public static BeanFactory getBeanFactory() throws IOException {
    if (beanFactory == null) {
        synchronized (beanFactoryLockObj) {
            if (beanFactory == null) {
                PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
                AbstractApplicationContext context = new ClassPathXmlApplicationContext(
                        "application-context.xml");

                Resource resource = new FileSystemResource("cma-cfg.properties");
                Properties properties = new Properties();
                properties.load(resource.getInputStream());

                configurer.setProperties(properties);

                context.addBeanFactoryPostProcessor(configurer);
                context.refresh();//  w w  w. ja v a  2s. c o  m

                beanFactory = context.getBeanFactory();
            }
        }
    }

    return beanFactory;
}

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();// ww w  .  ja  v a2 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;
}