下面列出了org.springframework.context.ApplicationContextAware#org.springframework.beans.factory.InitializingBean 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
@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);
}
}
}
};
}
@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);
}
}
/**
* 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;
}
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();
}
}
@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();
}
}
@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);
}
}
/**
* 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;
}
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);
}
}
@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");
}
};
}
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);
}
}
}
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);
}
}
}
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());
}
}
}
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);
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
if (viewResolver instanceof InitializingBean) {
((InitializingBean) viewResolver).afterPropertiesSet();
}
}
}
@Before
public final void createFactory() throws Exception {
this.factory = createRequestFactory();
if (this.factory instanceof InitializingBean) {
((InitializingBean) this.factory).afterPropertiesSet();
}
}
@Before
public final void createFactory() throws Exception {
factory = createRequestFactory();
if (factory instanceof InitializingBean) {
((InitializingBean) factory).afterPropertiesSet();
}
}
public void afterPropertiesSet() throws Exception {
if (connectionFactory instanceof InitializingBean) {
InitializingBean initializingBean = (InitializingBean) connectionFactory;
initializingBean.afterPropertiesSet();
}
mqTemplate.afterPropertiesSet();
}
@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);
}
}
});
}
}
@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));
};
}
@Before
public final void createFactory() throws Exception {
factory = createRequestFactory();
if (factory instanceof InitializingBean) {
((InitializingBean) factory).afterPropertiesSet();
}
}
/**
* 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);
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (executor instanceof InitializingBean) {
InitializingBean bean = (InitializingBean) executor;
bean.afterPropertiesSet();
}
}
@Bean
InitializingBean populateDatabase(CinemaRepository movieRepository) {
return () -> {
movieRepository.save(new Cinema(1, "Alamo", null));
movieRepository.save(new Cinema(2, "4DX", null));
};
}
@Bean
InitializingBean populateDatabase(CountryRepository countryRepository) {
return () -> {
countryRepository.save(new Country(1, "USA"));
countryRepository.save(new Country(2, "Ecuador"));
};
}
@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);
};
}
@Bean
public InitializingBean getInitialize()
{
return () -> {
if (!strictSSL)
{
HttpHelper.noStrictSSL();
}
};
}
@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();
};
}
/**
* After properties set.
*
* @throws Exception the exception
*/
@Override
public void afterPropertiesSet() throws Exception {
if (executor instanceof InitializingBean) {
InitializingBean bean = (InitializingBean) executor;
bean.afterPropertiesSet();
}
}
/**
* 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;
}