Java Code Examples for org.springframework.beans.factory.InitializingBean

The following examples show how to use org.springframework.beans.factory.InitializingBean. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: spring-analysis-note   Source File: StandaloneMockMvcBuilder.java    License: MIT License 6 votes vote down vote up
@Override
protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
	if (handlerExceptionResolvers == null) {
		return;
	}
	for (HandlerExceptionResolver resolver : handlerExceptionResolvers) {
		if (resolver instanceof ApplicationContextAware) {
			ApplicationContext applicationContext = getApplicationContext();
			if (applicationContext != null) {
				((ApplicationContextAware) resolver).setApplicationContext(applicationContext);
			}
		}
		if (resolver instanceof InitializingBean) {
			try {
				((InitializingBean) resolver).afterPropertiesSet();
			}
			catch (Exception ex) {
				throw new IllegalStateException("Failure from afterPropertiesSet", ex);
			}
		}
		exceptionResolvers.add(resolver);
	}
}
 
Example 2
@Bean
public InitializingBean clientsCorrelationInitializer(final RequestCorrelationProperties properties) {

    return new InitializingBean() {
        @Override
        public void afterPropertiesSet() throws Exception {

            if(clients != null) {
                for(InterceptingHttpAccessor client : clients) {
                    final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(client.getInterceptors());
                    interceptors.add(new ClientHttpRequestCorrelationInterceptor(properties));
                    client.setInterceptors(interceptors);
                }
            }
        }
    };
}
 
Example 3
Source Project: java-technology-stack   Source File: StandaloneMockMvcBuilder.java    License: MIT License 6 votes vote down vote up
@Override
protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
	if (handlerExceptionResolvers == null) {
		return;
	}
	for (HandlerExceptionResolver resolver : handlerExceptionResolvers) {
		if (resolver instanceof ApplicationContextAware) {
			ApplicationContext applicationContext  = getApplicationContext();
			if (applicationContext != null) {
				((ApplicationContextAware) resolver).setApplicationContext(applicationContext);
			}
		}
		if (resolver instanceof InitializingBean) {
			try {
				((InitializingBean) resolver).afterPropertiesSet();
			}
			catch (Exception ex) {
				throw new IllegalStateException("Failure from afterPropertiesSet", ex);
			}
		}
		exceptionResolvers.add(resolver);
	}
}
 
Example 4
/**
 * Create and start a new container using the specified factory.
 */
protected MessageListenerContainer createListenerContainer(JmsListenerEndpoint endpoint,
		JmsListenerContainerFactory<?> factory) {

	MessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint);

	if (listenerContainer instanceof InitializingBean) {
		try {
			((InitializingBean) listenerContainer).afterPropertiesSet();
		}
		catch (Exception ex) {
			throw new BeanInitializationException("Failed to initialize message listener container", ex);
		}
	}

	int containerPhase = listenerContainer.getPhase();
	if (containerPhase < Integer.MAX_VALUE) {  // a custom phase value
		if (this.phase < Integer.MAX_VALUE && this.phase != containerPhase) {
			throw new IllegalStateException("Encountered phase mismatch between container factory definitions: " +
					this.phase + " vs " + containerPhase);
		}
		this.phase = listenerContainer.getPhase();
	}

	return listenerContainer;
}
 
Example 5
public HdfsTextItemWriterFactory(Configuration configuration, JdbcHdfsTaskProperties props,
		String partitionSuffix ) throws Exception{
	List<FileNamingStrategy> strategies = new ArrayList<>();
	strategies.add(new StaticFileNamingStrategy(props.getFileName() + partitionSuffix));
	strategies.add(new RollingFileNamingStrategy());
	strategies.add(new StaticFileNamingStrategy(props.getFileExtension(), "."));
	ChainedFileNamingStrategy fileNamingStrategy = new ChainedFileNamingStrategy();
	fileNamingStrategy.setStrategies(strategies);
	RolloverStrategy rolloverStrategy = new SizeRolloverStrategy(props.getRollover());
	Path baseDirPath = new Path(props.getDirectory());
	setupConfiguration(configuration, props);
	OutputStreamWriter writer = new OutputStreamWriter(configuration, baseDirPath, null);
	writer.setInWritingSuffix(".tmp");
	writer.setFileNamingStrategy(fileNamingStrategy);
	writer.setRolloverStrategy(rolloverStrategy);
	hdfsTextItemWriter = new HdfsTextItemWriter();
	hdfsTextItemWriter.setLineAggregator(new org.springframework.batch.item.file.transform.PassThroughLineAggregator());
	hdfsTextItemWriter.setStoreWriter(writer);
	if (writer instanceof InitializingBean) {
		((InitializingBean) writer).afterPropertiesSet();
	}

}
 
Example 6
@Override
public void afterPropertiesSet() throws Exception {
	BeanWrapper bw = new BeanWrapperImpl(ThreadPoolTaskExecutor.class);
	determinePoolSizeRange(bw);
	if (this.queueCapacity != null) {
		bw.setPropertyValue("queueCapacity", this.queueCapacity);
	}
	if (this.keepAliveSeconds != null) {
		bw.setPropertyValue("keepAliveSeconds", this.keepAliveSeconds);
	}
	if (this.rejectedExecutionHandler != null) {
		bw.setPropertyValue("rejectedExecutionHandler", this.rejectedExecutionHandler);
	}
	if (this.beanName != null) {
		bw.setPropertyValue("threadNamePrefix", this.beanName + "-");
	}
	this.target = (TaskExecutor) bw.getWrappedInstance();
	if (this.target instanceof InitializingBean) {
		((InitializingBean) this.target).afterPropertiesSet();
	}
}
 
Example 7
@Override
protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
	if (handlerExceptionResolvers == null) {
		return;
	}
	for (HandlerExceptionResolver resolver : handlerExceptionResolvers) {
		if (resolver instanceof ApplicationContextAware) {
			((ApplicationContextAware) resolver).setApplicationContext(getApplicationContext());
		}
		if (resolver instanceof InitializingBean) {
			try {
				((InitializingBean) resolver).afterPropertiesSet();
			}
			catch (Exception ex) {
				throw new IllegalStateException("Failure from afterPropertiesSet", ex);
			}
		}
		exceptionResolvers.add(resolver);
	}
}
 
Example 8
/**
 * Create and start a new container using the specified factory.
 */
protected MessageListenerContainer createListenerContainer(JmsListenerEndpoint endpoint,
		JmsListenerContainerFactory<?> factory) {

	MessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint);

	if (listenerContainer instanceof InitializingBean) {
		try {
			((InitializingBean) listenerContainer).afterPropertiesSet();
		}
		catch (Exception ex) {
			throw new BeanInitializationException("Failed to initialize message listener container", ex);
		}
	}

	int containerPhase = listenerContainer.getPhase();
	if (containerPhase < Integer.MAX_VALUE) {  // a custom phase value
		if (this.phase < Integer.MAX_VALUE && this.phase != containerPhase) {
			throw new IllegalStateException("Encountered phase mismatch between container factory definitions: " +
					this.phase + " vs " + containerPhase);
		}
		this.phase = listenerContainer.getPhase();
	}

	return listenerContainer;
}
 
Example 9
Source Project: tddl5   Source File: AdapterDelegate.java    License: Apache License 2.0 6 votes vote down vote up
private TimestampPair createAdapter(String ip, int port, String user, String password) {
    CobarAdapter adapter = null;
    try {
        DataSource ds = dsFactory.createDataSource(ip, port, user, password);
        adapter = new CobarAdapter();
        adapter.setDataSource(ds);
        ((InitializingBean) adapter).afterPropertiesSet();
        return new TimestampPair(adapter);
    } catch (Exception exception) {
        logger.error("ip=" + ip + ", port=" + port, exception);
        try {
            adapter.destroy();
        } catch (Exception e) {
        }
        throw new RuntimeException(exception);
    }
}
 
Example 10
Source Project: flowable-engine   Source File: Application.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
InitializingBean usersAndGroupsInitializer(final IdentityService identityService) {

    return new InitializingBean() {
        @Override
        public void afterPropertiesSet() throws Exception {

            // install groups & users
            Group group = identityService.newGroup("user");
            group.setName("users");
            group.setType("security-role");
            identityService.saveGroup(group);

            User josh = identityService.newUser("jlong");
            josh.setFirstName("Josh");
            josh.setLastName("Long");
            josh.setPassword("password");
            identityService.saveUser(josh);

            identityService.createMembership("jlong", "user");
        }
    };
}
 
Example 11
Source Project: cuba   Source File: AppUI.java    License: Apache License 2.0 6 votes vote down vote up
protected void autowireContext(Object instance, ApplicationContext applicationContext) {
    AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    autowireBeanFactory.autowireBean(instance);

    if (instance instanceof ApplicationContextAware) {
        ((ApplicationContextAware) instance).setApplicationContext(applicationContext);
    }

    if (instance instanceof InitializingBean) {
        try {
            ((InitializingBean) instance).afterPropertiesSet();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to initialize UI Component - calling afterPropertiesSet for " +
                            instance.getClass(), e);
        }
    }
}
 
Example 12
Source Project: cuba   Source File: WebAbstractDataGrid.java    License: Apache License 2.0 6 votes vote down vote up
protected void autowireContext(Renderer instance) {
    AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    autowireBeanFactory.autowireBean(instance);

    if (instance instanceof ApplicationContextAware) {
        ((ApplicationContextAware) instance).setApplicationContext(applicationContext);
    }

    if (instance instanceof InitializingBean) {
        try {
            ((InitializingBean) instance).afterPropertiesSet();
        } catch (Exception e) {
            throw new RuntimeException("Unable to initialize Renderer - calling afterPropertiesSet for " +
                    instance.getClass(), e);
        }
    }
}
 
Example 13
Source Project: cuba   Source File: DesktopComponentsFactory.java    License: Apache License 2.0 6 votes vote down vote up
protected void autowireContext(Component instance) {
    AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    autowireBeanFactory.autowireBean(instance);

    if (instance instanceof ApplicationContextAware) {
        ((ApplicationContextAware) instance).setApplicationContext(applicationContext);
    }

    if (instance instanceof InitializingBean) {
        try {
            ((InitializingBean) instance).afterPropertiesSet();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to initialize Component - calling afterPropertiesSet for " +
                            instance.getClass());
        }
    }
}
 
Example 14
Source Project: cuba   Source File: ActionsImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected void autowireContext(Action instance) {
    AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    autowireBeanFactory.autowireBean(instance);

    if (instance instanceof ApplicationContextAware) {
        ((ApplicationContextAware) instance).setApplicationContext(applicationContext);
    }

    if (instance instanceof InitializingBean) {
        try {
            ((InitializingBean) instance).afterPropertiesSet();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to initialize UI Component - calling afterPropertiesSet for " +
                            instance.getClass(), e);
        }
    }
}
 
Example 15
Source Project: spring-analysis-note   Source File: ViewResolverComposite.java    License: MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	for (ViewResolver viewResolver : this.viewResolvers) {
		if (viewResolver instanceof InitializingBean) {
			((InitializingBean) viewResolver).afterPropertiesSet();
		}
	}
}
 
Example 16
@Before
public final void createFactory() throws Exception {
	this.factory = createRequestFactory();
	if (this.factory instanceof InitializingBean) {
		((InitializingBean) this.factory).afterPropertiesSet();
	}
}
 
Example 17
@Before
public final void createFactory() throws Exception {
	factory = createRequestFactory();
	if (factory instanceof InitializingBean) {
		((InitializingBean) factory).afterPropertiesSet();
	}
}
 
Example 18
Source Project: Thunder   Source File: MQHierachy.java    License: Apache License 2.0 5 votes vote down vote up
public void afterPropertiesSet() throws Exception {
    if (connectionFactory instanceof InitializingBean) {
        InitializingBean initializingBean = (InitializingBean) connectionFactory;
        initializingBean.afterPropertiesSet();
    }
    mqTemplate.afterPropertiesSet();
}
 
Example 19
Source Project: mPaaS   Source File: CompositeFilterProxy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void initFilterBean() throws ServletException {
    super.initFilterBean();
    List<Filter> innerFilters = new ArrayList<Filter>(1);
    if (!CollectionUtils.isEmpty(filterDefs)) {
        // 按order注解定义优先级处理
        AnnotationAwareOrderComparator.sort(filterDefs);
        for (IWebFilterDef filterDef : filterDefs) {
            if (filterDef.support(this.getClass())) {
                innerFilters.add(filterDef.getFilterInstance());
            }
        }
    }
    handleInnerFilters(innerFilters);
    innerFilters.forEach((filter) -> {
        if (filter instanceof EnvironmentAware) {
            ((EnvironmentAware) filter).setEnvironment(this.getEnvironment());
        }
    });
    compositeFilter.setFilters(innerFilters);
    if (getFilterConfig() != null) {
        //web容器启动
        compositeFilter.init(getFilterConfig());
    } else {
        //非容器自启动
        innerFilters.forEach((filter) -> {
            if (filter instanceof InitializingBean) {
                try {
                    ((InitializingBean) filter).afterPropertiesSet();
                } catch (Exception e) {
                    log.warn(filter.getClass().getName() + "初始化错误", e);
                }
            }
        });
    }

}
 
Example 20
Source Project: building-microservices   Source File: DataJpaApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public InitializingBean seedDatabase(CarRepository repository) {
	return () -> {
		repository.save(new Car("Honda", "Civic", 1997));
		repository.save(new Car("Honda", "Accord", 2003));
		repository.save(new Car("Ford", "Escort", 1985));
	};
}
 
Example 21
@Before
public final void createFactory() throws Exception {
	factory = createRequestFactory();
	if (factory instanceof InitializingBean) {
		((InitializingBean) factory).afterPropertiesSet();
	}
}
 
Example 22
/**
 * Give a bean a chance to react now all its properties are set,
 * and a chance to know about its owning bean factory (this object).
 * This means checking whether the bean implements InitializingBean or defines
 * a custom init method, and invoking the necessary callback(s) if it does.
 * @param beanName the bean name in the factory (for debugging purposes)
 * @param bean the new bean instance we may need to initialize
 * @param mbd the merged bean definition that the bean was created with
 * (can also be {@code null}, if given an existing bean instance)
 * @throws Throwable if thrown by init methods or by the invocation process
 * @see #invokeCustomInitMethod
 */
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
		throws Throwable {

	boolean isInitializingBean = (bean instanceof InitializingBean);
	if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
		if (logger.isTraceEnabled()) {
			logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
		}
		if (System.getSecurityManager() != null) {
			try {
				AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
					((InitializingBean) bean).afterPropertiesSet();
					return null;
				}, getAccessControlContext());
			}
			catch (PrivilegedActionException pae) {
				throw pae.getException();
			}
		}
		else {
			((InitializingBean) bean).afterPropertiesSet();
		}
	}

	if (mbd != null && bean.getClass() != NullBean.class) {
		String initMethodName = mbd.getInitMethodName();
		if (StringUtils.hasLength(initMethodName) &&
				!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
				!mbd.isExternallyManagedInitMethod(initMethodName)) {
			invokeCustomInitMethod(beanName, bean, mbd);
		}
	}
}
 
Example 23
@Override
public void afterPropertiesSet() throws Exception {
    if (executor instanceof InitializingBean) {
        InitializingBean bean = (InitializingBean) executor;
        bean.afterPropertiesSet();
    }
}
 
Example 24
@Bean
InitializingBean populateDatabase(CinemaRepository movieRepository) {
    return () -> {
        movieRepository.save(new Cinema(1, "Alamo", null));
        movieRepository.save(new Cinema(2, "4DX", null));
    };
}
 
Example 25
@Bean
InitializingBean populateDatabase(CountryRepository countryRepository) {
    return () -> {
        countryRepository.save(new Country(1, "USA"));
        countryRepository.save(new Country(2, "Ecuador"));
    };
}
 
Example 26
@Bean
public InitializingBean prepareQueues(AmqpAdmin amqpAdmin) {
	return () -> {
		Queue queue = new Queue(NOTIFICATIONS, true);
		DirectExchange exchange = new DirectExchange(NOTIFICATIONS);
		Binding binding = BindingBuilder.bind(queue).to(exchange).with(NOTIFICATIONS);
		amqpAdmin.declareQueue(queue);
		amqpAdmin.declareExchange(exchange);
		amqpAdmin.declareBinding(binding);

	};
}
 
Example 27
Source Project: egeria   Source File: EgeriaUIPlatform.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public InitializingBean getInitialize()
{
    return () -> {
        if (!strictSSL)
        {
            HttpHelper.noStrictSSL();
        }
    };
}
 
Example 28
Source Project: egeria   Source File: OMAGServerPlatform.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public InitializingBean getInitialize()
{
    return () -> {
        if (!strictSSL)
        {
            log.warn("strict.ssl is set to false! Invalid certificates will be accepted for connection!");
            HttpHelper.noStrictSSL();
        }
        autoStartConfig();
    };
}
 
Example 29
/**
 * After properties set.
 *
 * @throws Exception the exception
 */
@Override
public void afterPropertiesSet() throws Exception {
	if (executor instanceof InitializingBean) {
		InitializingBean bean = (InitializingBean) executor;
		bean.afterPropertiesSet();
	}
}
 
Example 30
Source Project: micronaut-spring   Source File: SpringAwareListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute when a bean is created.
 * @param bean The bean.
 * @return The result
 */
public Object onBeanCreated(Object bean) {
    wireAwareObjects(bean);
    if (bean instanceof InitializingBean) {
        try {
            ((InitializingBean) bean).afterPropertiesSet();
        } catch (Exception e) {
            throw new BeanCreationException(e.getMessage(), e);
        }
    }
    return bean;
}