Example usage for org.springframework.context.support GenericApplicationContext addBeanFactoryPostProcessor

List of usage examples for org.springframework.context.support GenericApplicationContext addBeanFactoryPostProcessor

Introduction

In this page you can find the example usage for org.springframework.context.support GenericApplicationContext addBeanFactoryPostProcessor.

Prototype

@Override
    public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) 

Source Link

Usage

From source file:exercise.cca.data.cli.main.MainCli.java

protected static ConfigurableApplicationContext loadContext(final String contextPath) {
    final GenericApplicationContext ctx = new GenericApplicationContext();
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource(contextPath));
    final PropertyPlaceholderConfigurer placeholderProcessor = new PropertyPlaceholderConfigurer();
    ctx.addBeanFactoryPostProcessor(placeholderProcessor);
    ctx.refresh();//w  w  w . ja  va  2 s .co m
    return ctx;
}

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;// w w w  . j a v  a  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: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 . j  a  v a  2s. c  om

    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:org.joinfaces.annotations.JsfCdiToSpringApplicationBeanFactoryPostProcessorIT.java

@Test
public void testNoScopedClass() {
    GenericApplicationContext acx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(acx);

    acx.registerBeanDefinition("noScopedClass",
            new AnnotatedGenericBeanDefinition(new StandardAnnotationMetadata(NoScopedClass.class)));
    acx.registerBeanDefinition("scopedBeansConfiguration",
            new RootBeanDefinition(ScopedBeansConfiguration.class));
    acx.addBeanFactoryPostProcessor(new JsfCdiToSpringBeanFactoryPostProcessor());
    acx.refresh();/*from   w  w w .ja va  2 s .  c om*/

    assertThat(acx.getBeanDefinition("noScopedClass").getScope()).isEqualTo("");
    assertThat(acx.getBeanDefinition("noScopedBean").getScope()).isEqualTo("");

}

From source file:org.joinfaces.annotations.JsfCdiToSpringApplicationBeanFactoryPostProcessorIT.java

@Test
public void testViewScopedClass() {
    GenericApplicationContext acx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(acx);

    acx.registerBeanDefinition("viewScopedClass",
            new AnnotatedGenericBeanDefinition(new StandardAnnotationMetadata(ViewScopedClass.class)));
    acx.registerBeanDefinition("scopedBeansConfiguration",
            new RootBeanDefinition(ScopedBeansConfiguration.class));
    acx.addBeanFactoryPostProcessor(new JsfCdiToSpringBeanFactoryPostProcessor());
    acx.refresh();//from  w ww.j a v a 2 s.  c  o  m

    assertThat(acx.getBeanDefinition("viewScopedClass").getScope()).isEqualTo(JsfCdiToSpring.VIEW);
    assertThat(acx.getBeanDefinition("viewScopedBean").getScope()).isEqualTo(JsfCdiToSpring.VIEW);
}

From source file:org.joinfaces.annotations.JsfCdiToSpringApplicationBeanFactoryPostProcessorIT.java

@Test
public void testSessionScopedClass() {
    GenericApplicationContext acx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(acx);

    acx.registerBeanDefinition("sessionScopedClass",
            new AnnotatedGenericBeanDefinition(new StandardAnnotationMetadata(SessionScopedClass.class)));
    acx.registerBeanDefinition("scopedBeansConfiguration",
            new RootBeanDefinition(ScopedBeansConfiguration.class));
    acx.addBeanFactoryPostProcessor(new JsfCdiToSpringBeanFactoryPostProcessor());
    acx.refresh();/*from   ww  w. j  a  v  a2 s. com*/

    assertThat(acx.getBeanDefinition("sessionScopedClass").getScope()).isEqualTo(JsfCdiToSpring.SESSION);
    assertThat(acx.getBeanDefinition("sessionScopedBean").getScope()).isEqualTo(JsfCdiToSpring.SESSION);
}

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 .java  2  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:nz.co.senanque.madura.bundle.BundleRootImpl.java

public void init(DefaultListableBeanFactory ownerBeanFactory, Properties properties, ClassLoader cl,
        Map<String, Object> inheritableBeans) {
    m_properties = properties;// w w w  .j  a v a  2  s .c  o  m
    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);
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/**
 * Prepares Spring context.//  w  w w. j a  va 2s  .c o  m
 *
 * @param excludedProps Properties to be excluded.
 * @return application context.
 */
private static GenericApplicationContext prepareSpringContext(final String... excludedProps) {
    GenericApplicationContext springCtx = new GenericApplicationContext();

    if (excludedProps.length > 0) {
        final List<String> excludedPropsList = Arrays.asList(excludedProps);

        BeanFactoryPostProcessor postProc = new BeanFactoryPostProcessor() {
            /**
             * @param def Registered BeanDefinition.
             * @throws BeansException in case of errors.
             */
            private void processNested(BeanDefinition def) throws BeansException {
                Iterator<PropertyValue> iterVals = def.getPropertyValues().getPropertyValueList().iterator();

                while (iterVals.hasNext()) {
                    PropertyValue val = iterVals.next();

                    if (excludedPropsList.contains(val.getName())) {
                        iterVals.remove();

                        continue;
                    }

                    if (val.getValue() instanceof Iterable) {
                        Iterator iterNested = ((Iterable) val.getValue()).iterator();

                        while (iterNested.hasNext()) {
                            Object item = iterNested.next();

                            if (item instanceof BeanDefinitionHolder) {
                                BeanDefinitionHolder h = (BeanDefinitionHolder) item;

                                try {
                                    if (h.getBeanDefinition().getBeanClassName() != null)
                                        Class.forName(h.getBeanDefinition().getBeanClassName());

                                    processNested(h.getBeanDefinition());
                                } catch (ClassNotFoundException ignored) {
                                    iterNested.remove();
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
                    throws BeansException {
                for (String beanName : beanFactory.getBeanDefinitionNames()) {
                    try {
                        BeanDefinition def = beanFactory.getBeanDefinition(beanName);

                        if (def.getBeanClassName() != null)
                            Class.forName(def.getBeanClassName());

                        processNested(def);
                    } catch (ClassNotFoundException ignored) {
                        ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName);
                    }
                }
            }
        };

        springCtx.addBeanFactoryPostProcessor(postProc);
    }

    return springCtx;
}

From source file:org.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java

/**
 * Creates Spring application context. Optionally excluded properties can be specified,
 * it means that if such a property is found in {@link GridConfiguration}
 * then it is removed before the bean is instantiated.
 * For example, {@code streamerConfiguration} can be excluded from the configs that Visor uses.
 *
 * @param cfgUrl Resource where config file is located.
 * @param excludedProps Properties to be excluded.
 * @return Spring application context./*from   w  w w.ja  v a2s  .c o m*/
 */
public static ApplicationContext applicationContext(URL cfgUrl, final String... excludedProps) {
    GenericApplicationContext springCtx = new GenericApplicationContext();

    BeanFactoryPostProcessor postProc = new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {
                BeanDefinition def = beanFactory.getBeanDefinition(beanName);

                if (def.getBeanClassName() != null) {
                    try {
                        Class.forName(def.getBeanClassName());
                    } catch (ClassNotFoundException ignored) {
                        ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName);

                        continue;
                    }
                }

                MutablePropertyValues vals = def.getPropertyValues();

                for (PropertyValue val : new ArrayList<>(vals.getPropertyValueList())) {
                    for (String excludedProp : excludedProps) {
                        if (val.getName().equals(excludedProp))
                            vals.removePropertyValue(val);
                    }
                }
            }
        }
    };

    springCtx.addBeanFactoryPostProcessor(postProc);

    new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl));

    springCtx.refresh();

    return springCtx;
}