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

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

Introduction

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

Prototype

BeanFactoryPostProcessor

Source Link

Usage

From source file:de.extra.client.starter.ApplicationContextStarter.java

/**
 * Startet einen Spring-Context mit extern definierten Beans. Diese Beans
 * werden im Spring-Context als Singleton registriert.
 *
 * @param preregisteredObjects/*w  ww.j  a  v  a2 s .c om*/
 *            Map mit den vordefinierten Beans.
 * @return iniitalisierter {@link ApplicationContext}
 */
public C createApplicationContext(final Map<String, Object> preregisteredObjects) {
    final C context = createUninitializedContext();
    final BeanFactoryPostProcessor beanFactoryPostProcessor = new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory)
                throws BeansException {
            for (final Map.Entry<String, Object> entry : preregisteredObjects.entrySet()) {
                beanFactory.registerSingleton(entry.getKey(), entry.getValue());
            }
        }
    };
    context.addBeanFactoryPostProcessor(beanFactoryPostProcessor);
    context.refresh();
    return context;
}

From source file:org.loginject.SpringLogInjectionService.java

@Override
public BeanFactoryPostProcessor getBindings(LogInject<_Logger_> logInject) {
    return new BeanFactoryPostProcessor() {
        ThreadLocal<Object> injectee = new ThreadLocal<>();

        @Override//from   w w w. j  ava 2  s .c om
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
            AutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver() {
                @Override
                public Object getSuggestedValue(DependencyDescriptor descriptor) {
                    if (descriptor.getDependencyType().equals(logInject.getLoggerClass())) {
                        return logInject.createLogger(injectee.get().getClass());
                    }
                    return null;
                }
            };
            AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor() {
                @Override
                public PropertyValues postProcessPropertyValues(PropertyValues values,
                        PropertyDescriptor[] descriptors, Object bean, String beanName) throws BeansException {
                    injectee.set(bean);
                    return super.postProcessPropertyValues(values, descriptors, bean, beanName);
                }
            };
            beanPostProcessor.setBeanFactory(defaultListableBeanFactory);
            defaultListableBeanFactory.addBeanPostProcessor(beanPostProcessor);
            defaultListableBeanFactory.setAutowireCandidateResolver(resolver);
        }
    };
}

From source file:cross.applicationContext.DefaultApplicationContextFactory.java

/**
 * Creates a new application context from the current list of
 * <code>applicationContextPaths</code>, interpreted as file system
 * resources, and the current//from   www . jav  a  2s . c  o  m
 * <code>configuration</code>.
 *
 * @return the application context
 * @throws BeansException if any beans are not configured correctly
 */
public ApplicationContext createApplicationContext() throws BeansException {
    AbstractRefreshableApplicationContext context = null;
    try {
        final ConfiguringBeanPostProcessor cbp = new ConfiguringBeanPostProcessor();
        cbp.setConfiguration(configuration);
        context = new FileSystemXmlApplicationContext(
                applicationContextPaths.toArray(new String[applicationContextPaths.size()]), context);
        context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory clbf) throws BeansException {
                clbf.addBeanPostProcessor(cbp);
            }
        });
        context.refresh();
    } catch (BeansException e2) {
        throw e2;
    }
    return context;
}

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();//  w w  w.  ja  v a  2  s. com

    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.jasig.portlet.calendar.util.MockWebApplicationContextLoader.java

public ApplicationContext loadContext(String... locations) throws Exception {
    // Establish the portlet context and config based on the test class's MockWebApplication annotation.
    MockServletContext mockServletContext = new MockServletContext(configuration.webapp(),
            new FileSystemResourceLoader());
    final ServletWrappingPortletContext portletContext = new ServletWrappingPortletContext(mockServletContext);
    final MockPortletConfig portletConfig = new MockPortletConfig(portletContext, configuration.name());

    // Create a WebApplicationContext and initialize it with the xml and portlet configuration.
    final XmlPortletApplicationContext portletApplicationContext = new XmlPortletApplicationContext();
    portletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            portletApplicationContext);//from w ww  .  j a  v a2 s  . com
    portletApplicationContext.setPortletConfig(portletConfig);
    portletApplicationContext.setConfigLocations(locations);

    // Create a DispatcherPortlet that uses the previously established WebApplicationContext.
    final DispatcherPortlet dispatcherPortlet = new DispatcherPortlet() {
        @Override
        protected WebApplicationContext createPortletApplicationContext(ApplicationContext parent) {
            return portletApplicationContext;
        }
    };

    final ViewResolver viewResolver = new MockViewResolver();

    // Add the DispatcherPortlet (and anything else you want) to the context.
    // Note: this doesn't happen until refresh is called below.
    portletApplicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.registerResolvableDependency(DispatcherPortlet.class, dispatcherPortlet);
            // Register any other beans here, including a ViewResolver if you are using JSPs.
            beanFactory.registerResolvableDependency(ViewResolver.class, viewResolver);
        }
    });

    // Have the context notify the portlet every time it is refreshed.
    portletApplicationContext.addApplicationListener(new SourceFilteringListener(portletApplicationContext,
            new ApplicationListener<ContextRefreshedEvent>() {
                public void onApplicationEvent(ContextRefreshedEvent event) {
                    dispatcherPortlet.onApplicationEvent(event);
                }
            }));

    // Prepare the context.
    portletApplicationContext.refresh();
    portletApplicationContext.registerShutdownHook();

    // Initialize the portlet.
    dispatcherPortlet.setContextConfigLocation("");
    dispatcherPortlet.init(portletConfig);

    return portletApplicationContext;
}

From source file:com.github.carlomicieli.nerdmovies.MockWebApplicationContextLoader.java

@Override
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
    final MockServletContext servletContext = new MockServletContext(configuration.webapp(),
            new FileSystemResourceLoader());
    final MockServletConfig servletConfig = new MockServletConfig(servletContext, configuration.name());

    final AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
    webContext.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles());
    webContext.setServletConfig(servletConfig);
    webContext.setConfigLocations(mergedConfig.getLocations());
    webContext.register(mergedConfig.getClasses());

    // Create a DispatcherServlet that uses the previously established
    // WebApplicationContext.
    @SuppressWarnings("serial")
    final DispatcherServlet dispatcherServlet = new DispatcherServlet() {
        @Override/*  ww w  .  ja v a  2 s.c o m*/
        protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
            return webContext;
        }
    };

    // Add the DispatcherServlet (and anything else you want) to the
    // context.
    // Note: this doesn't happen until refresh is called below.
    webContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.registerResolvableDependency(DispatcherServlet.class, dispatcherServlet);
            // Register any other beans here, including a ViewResolver if
            // you are using JSPs.
        }
    });

    // Have the context notify the servlet every time it is refreshed.
    webContext.addApplicationListener(
            new SourceFilteringListener(webContext, new ApplicationListener<ContextRefreshedEvent>() {
                @Override
                public void onApplicationEvent(ContextRefreshedEvent event) {
                    dispatcherServlet.onApplicationEvent(event);
                }
            }));

    // Prepare the context.
    webContext.refresh();
    webContext.registerShutdownHook();

    // Initialize the servlet.
    dispatcherServlet.setContextConfigLocation("");
    dispatcherServlet.init(servletConfig);

    return webContext;
}

From source file:co.paralleluniverse.galaxy.Grid.java

private Grid(String configFile, Object properties) throws InterruptedException {
    if (configFile == null)
        configFile = System.getProperty("co.paralleluniverse.galaxy.configFile");
    if (properties == null)
        properties = System.getProperty("co.paralleluniverse.galaxy.propertiesFile");
    this.context = SpringContainerHelper.createContext("co.paralleluniverse.galaxy",
            configFile != null ? new FileSystemResource(configFile) : new ClassPathResource("galaxy.xml"),
            properties instanceof String ? new FileSystemResource((String) properties) : properties,
            new BeanFactoryPostProcessor() {
                @Override/*from   w  w w  .ja v  a 2s.  co  m*/
                public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory1)
                        throws BeansException {
                    final DefaultListableBeanFactory beanFactory = ((DefaultListableBeanFactory) beanFactory1);

                    // messenger
                    //                        BeanDefinition messengerBeanDefinition = SpringContainerHelper.defineBean(
                    //                                MessengerImpl.class,
                    //                                SpringContainerHelper.constructorArgs("messenger", new RuntimeBeanReference("cache")),
                    //                                null);
                    //                        messengerBeanDefinition.setDependsOn(new String[]{"cache"});
                    //                        beanFactory.registerBeanDefinition("messenger", messengerBeanDefinition);

                    //beanFactory.registerSingleton(name, object);
                }
            });
    this.cluster = context.getBean("cluster", Cluster.class);
    this.clusterMonitor = new ClusterMonitor(cluster);

    this.backup = context.getBean("backup", Backup.class);

    this.cache = context.getBean("cache", Cache.class);
    this.store = new StoreImpl(cache);
    this.messenger = context.getBean("messenger", Messenger.class); // new MessengerImpl(cache);
}

From source file:cross.applicationContext.DefaultApplicationContextFactory.java

/**
 * Creates a new application context from the current list of
 * <code>applicationContextPaths</code>, interpreted as class path
 * resources, and the current <code>configuration</code>.
 *
 * @return the application context//from  w  w  w  . j  a  v a  2 s  .co  m
 * @throws BeansException if any beans are not configured correctly
 */
public ApplicationContext createClassPathApplicationContext() throws BeansException {
    AbstractRefreshableApplicationContext context = null;
    try {
        final ConfiguringBeanPostProcessor cbp = new ConfiguringBeanPostProcessor();
        cbp.setConfiguration(configuration);
        context = new ClassPathXmlApplicationContext(
                applicationContextPaths.toArray(new String[applicationContextPaths.size()]), context);
        context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory clbf) throws BeansException {
                clbf.addBeanPostProcessor(cbp);
            }
        });
        context.refresh();
    } catch (BeansException e2) {
        throw e2;
    }
    return context;
}

From source file:com.ms.commons.test.BaseTestCase.java

/**
 * Service???//  w  w  w .j  a v a  2  s .  c  o  m
 * 
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
protected void initMoke() throws InstantiationException, IllegalAccessException {
    // Mock once on startup
    if (isMockOn()) {

        if (log.isDebugEnabled()) {
            log.debug("================>initMock!");
        }
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) CommonServiceLocator
                .getApplicationContext();
        context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {

            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
                    throws BeansException {
                beanFactory.addBeanPostProcessor(new MockBeanPostProcessor());
            }
        });
        context.refresh();
    }
}

From source file:no.kantega.publishing.spring.OpenAksessContextLoaderListener.java

private void addConfigurationPropertyReplacer(ConfigurableWebApplicationContext wac,
        final Properties properties) {
    wac.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            cfg.setProperties(properties);
            cfg.postProcessBeanFactory(beanFactory);
        }//www  .j a  v a2 s.  com
    });
}