Java Code Examples for org.springframework.context.ConfigurableApplicationContext#addBeanFactoryPostProcessor()

The following examples show how to use org.springframework.context.ConfigurableApplicationContext#addBeanFactoryPostProcessor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BeanFactoryPostProcessorBootstrap.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("factory.bean/factory-post-processor.xml");
	BeanFactoryPostProcessor beanFactoryPostProcessor = (BeanFactoryPostProcessor) context.getBean("carPostProcessor");
	beanFactoryPostProcessor.postProcessBeanFactory(context.getBeanFactory());
	// 输出 :Car{maxSpeed=0, brand='*****', price=10000.0},敏感词被替换了
	System.out.println(context.getBean("car"));

	// 硬编码 后处理器执行时间
	BeanFactoryPostProcessor hardCodeBeanFactoryPostProcessor = new HardCodeBeanFactoryPostProcessor();
	context.addBeanFactoryPostProcessor(hardCodeBeanFactoryPostProcessor);
	// 更新上下文
	context.refresh();
	// 输出 :
	// Hard Code BeanFactory Post Processor execute time
	// Car{maxSpeed=0, brand='*****', price=10000.0}
	System.out.println(context.getBean("car"));
}
 
Example 2
Source File: EmbeddedPostgresContextCustomizerFactory.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
    context.addBeanFactoryPostProcessor(new EnvironmentPostProcessor(context.getEnvironment()));

    BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context);
    RootBeanDefinition registrarDefinition = new RootBeanDefinition();

    registrarDefinition.setBeanClass(PreloadableEmbeddedPostgresRegistrar.class);
    registrarDefinition.getConstructorArgumentValues()
            .addIndexedArgumentValue(0, databaseAnnotations);

    registry.registerBeanDefinition("preloadableEmbeddedPostgresRegistrar", registrarDefinition);
}
 
Example 3
Source File: DubboConfigurationApplicationContextInitializer.java    From spring-boot-starter-dubbo with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    Environment env = applicationContext.getEnvironment();
    String scan = env.getProperty("spring.dubbo.scan");
    if (scan != null) {
        AnnotationBean scanner = BeanUtils.instantiate(AnnotationBean.class);
        scanner.setPackage(scan);
        scanner.setApplicationContext(applicationContext);
        applicationContext.addBeanFactoryPostProcessor(scanner);
        applicationContext.getBeanFactory().addBeanPostProcessor(scanner);
        applicationContext.getBeanFactory().registerSingleton("annotationBean", scanner);
    }

}
 
Example 4
Source File: JuneauRestInitializer.java    From juneau with Apache License 2.0 5 votes vote down vote up
@Override /* ApplicationContextInitializer */
public void initialize(ConfigurableApplicationContext ctx) {
	String port = ctx.getEnvironment().getProperty("server.port");
	if (port != null && getProperty("juneau.serverPort") == null)
		setProperty("juneau.serverPort", port);
	ctx.addBeanFactoryPostProcessor(new JuneauRestPostProcessor(ctx, appClass));
}
 
Example 5
Source File: DubboApplicationContextInitializer.java    From dubbo-spring-boot-project with Apache License 2.0 4 votes vote down vote up
private void overrideBeanDefinitions(ConfigurableApplicationContext applicationContext) {
    applicationContext.addBeanFactoryPostProcessor(new OverrideBeanDefinitionRegistryPostProcessor());
    // @since 2.7.5 DubboConfigBeanDefinitionConflictProcessor has been removed
    // @see {@link DubboConfigBeanDefinitionConflictApplicationListener}
    // applicationContext.addBeanFactoryPostProcessor(new DubboConfigBeanDefinitionConflictProcessor());
}
 
Example 6
Source File: FountainConsumerApplicationContextInitializer.java    From fountain with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
    applicationContext.addBeanFactoryPostProcessor(
            new CustomConsumerFactoryPostProcessor(consumeActorXmlPath, applicationContext));
}
 
Example 7
Source File: FunctionalSpringApplication.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
	super.postProcessApplicationContext(context);
	boolean functional = false;
	Assert.isInstanceOf(GenericApplicationContext.class, context,
			"ApplicationContext must be an instanceof GenericApplicationContext");
	for (Object source : getAllSources()) {
		Class<?> type = null;
		Object handler = null;
		if (source instanceof String) {
			String name = (String) source;
			if (ClassUtils.isPresent(name, null)) {
				type = ClassUtils.resolveClassName(name, null);
			}
		}
		else if (source instanceof Class<?>) {
			type = (Class<?>) source;
		}
		else {
			type = source.getClass();
			handler = source;
		}
		if (ApplicationContextInitializer.class.isAssignableFrom(type)) {
			if (handler == null) {
				handler = BeanUtils.instantiateClass(type);
			}

			ApplicationContextInitializer<ConfigurableApplicationContext> initializer =
					(ApplicationContextInitializer<ConfigurableApplicationContext>) handler;
			initializer.initialize(context);
			functional = true;
		}
		else if (Function.class.isAssignableFrom(type)
				|| Consumer.class.isAssignableFrom(type)
				|| Supplier.class.isAssignableFrom(type)) {
			Class<?> functionType = type;
			Object function = handler;
			if (source.equals(functionType)) {
				context.addBeanFactoryPostProcessor(beanFactory -> {
					BeanDefinitionRegistry bdRegistry = (BeanDefinitionRegistry) beanFactory;
					if (!ObjectUtils.isEmpty(context.getBeanNamesForType(functionType))) {
						stream(context.getBeanNamesForType(functionType))
						.forEach(beanName -> bdRegistry.registerAlias(beanName, "function"));
					}
					else {
						this.register((GenericApplicationContext) context, function, functionType);
					}
				});
			}
			else {
				this.register((GenericApplicationContext) context, function, functionType);
			}
			functional = true;
		}
	}
	if (functional) {
		defaultProperties(context);
	}
}
 
Example 8
Source File: TestComponentManagerContainer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * create a component manager based on a list of component.xml
 * @param configPaths a ';' seperated list of xml bean config files
 * @throws IOException
 */
public TestComponentManagerContainer(String configPaths, Properties props)  throws IOException {
	// we assume that all the jars are in the same classloader, so this will
	// not check for
	// incorrect bindings and will not fully replicate the tomcat
	// experience, but is an easier environment
	// to work within for kernel testing.
	// For a more complex structure we could use the kernel poms in the repo
	// to generate the dep list.
	if ( ComponentManager.m_componentManager != null ) {
		log.info("Closing existing Component Manager ");
		/*			
			try {
			ComponentManager.m_componentManager.close();
		} catch ( Throwable t ) {
			log.warn("Close Failed with message, safe to ignore "+t.getMessage());
		}
		*/
		log.info("Closing Complete ");
		ComponentManager.m_componentManager = null;
	}
	
	log.info("Starting Component Manager with ["+configPaths+"]");
	ComponentManager.setLateRefresh(true);

	componentManager = (SpringCompMgr) ComponentManager.getInstance();
	ConfigurableApplicationContext ac = componentManager.getApplicationContext();
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	// Supply any additional configuration.
	if (props != null) {
		PropertyOverrideConfigurer beanFactoryPostProcessor = new PropertyOverrideConfigurer();
		beanFactoryPostProcessor.setBeanNameSeparator("@");
		beanFactoryPostProcessor.setProperties(props);
		ac.addBeanFactoryPostProcessor(beanFactoryPostProcessor);
	}

	// we could take the kernel bootstrap from from the classpath in future
	// rather than from
	// the filesystem

	List<Resource> config = new ArrayList<Resource>();
	String[] configPath = configPaths.split(";");
	for ( String p : configPath) {
		File xml = new File(p);
		config.add(new FileSystemResource(xml.getCanonicalPath()));
	}
	loadComponent(ac, config, classLoader);
	
	ac.refresh();

	// SAK-20908 - band-aid for TLM sync issues causing tests to fail
	// This sleep shouldn't be needed but it seems these tests are starting before ThreadLocalManager has finished its startup.
       try {
           Thread.sleep(500); // 1/2 second
           log.debug("Finished starting the component manager");
       } catch (InterruptedException e) {
           log.error("Component manager startup interrupted...");
       }
}
 
Example 9
Source File: TestComponentManagerContainer.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * create a component manager based on a list of component.xml
 * @param configPaths a ';' seperated list of xml bean config files
 * @throws IOException
 */
public TestComponentManagerContainer(String configPaths, Properties props)  throws IOException {
	// we assume that all the jars are in the same classloader, so this will
	// not check for
	// incorrect bindings and will not fully replicate the tomcat
	// experience, but is an easier environment
	// to work within for kernel testing.
	// For a more complex structure we could use the kernel poms in the repo
	// to generate the dep list.
	if ( ComponentManager.m_componentManager != null ) {
		log.info("Closing existing Component Manager ");
		/*			
			try {
			ComponentManager.m_componentManager.close();
		} catch ( Throwable t ) {
			log.warn("Close Failed with message, safe to ignore "+t.getMessage());
		}
		*/
		log.info("Closing Complete ");
		ComponentManager.m_componentManager = null;
	}
	
	log.info("Starting Component Manager with ["+configPaths+"]");
	ComponentManager.setLateRefresh(true);

	componentManager = (SpringCompMgr) ComponentManager.getInstance();
	ConfigurableApplicationContext ac = componentManager.getApplicationContext();
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	// Supply any additional configuration.
	if (props != null) {
		PropertyOverrideConfigurer beanFactoryPostProcessor = new PropertyOverrideConfigurer();
		beanFactoryPostProcessor.setBeanNameSeparator("@");
		beanFactoryPostProcessor.setProperties(props);
		ac.addBeanFactoryPostProcessor(beanFactoryPostProcessor);
	}

	// we could take the kernel bootstrap from from the classpath in future
	// rather than from
	// the filesystem

	List<Resource> config = new ArrayList<Resource>();
	String[] configPath = configPaths.split(";");
	for ( String p : configPath) {
		File xml = new File(p);
		config.add(new FileSystemResource(xml.getCanonicalPath()));
	}
	loadComponent(ac, config, classLoader);
	
	ac.refresh();

	// SAK-20908 - band-aid for TLM sync issues causing tests to fail
	// This sleep shouldn't be needed but it seems these tests are starting before ThreadLocalManager has finished its startup.
       try {
           Thread.sleep(500); // 1/2 second
           log.debug("Finished starting the component manager");
       } catch (InterruptedException e) {
           log.error("Component manager startup interrupted...");
       }
}