org.springframework.beans.factory.InitializingBean Java Examples

The following examples show how to use org.springframework.beans.factory.InitializingBean. 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: StandaloneMockMvcBuilder.java    From spring-analysis-note with 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
Source File: ClientHttpCorrelationConfiguration.java    From request-correlation-spring-cloud-starter with Apache License 2.0 6 votes vote down vote up
@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 File: StandaloneMockMvcBuilder.java    From java-technology-stack with 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
Source File: JmsListenerEndpointRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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
Source File: HdfsTextItemWriterFactory.java    From spring-cloud-task-app-starters with Apache License 2.0 6 votes vote down vote up
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
Source File: TaskExecutorFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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
Source File: StandaloneMockMvcBuilder.java    From spring4-understanding with Apache License 2.0 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) {
			((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
Source File: JmsListenerEndpointRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 File: AdapterDelegate.java    From tddl5 with 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 File: Application.java    From flowable-engine with 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 File: AppUI.java    From cuba with 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 File: WebAbstractDataGrid.java    From cuba with 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 File: DesktopComponentsFactory.java    From cuba with 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 File: ActionsImpl.java    From cuba with 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 File: ViewResolverComposite.java    From spring-analysis-note with 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
Source File: AbstractAsyncHttpRequestFactoryTestCase.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public final void createFactory() throws Exception {
	this.factory = createRequestFactory();
	if (this.factory instanceof InitializingBean) {
		((InitializingBean) this.factory).afterPropertiesSet();
	}
}
 
Example #17
Source File: AbstractHttpRequestFactoryTestCase.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public final void createFactory() throws Exception {
	factory = createRequestFactory();
	if (factory instanceof InitializingBean) {
		((InitializingBean) factory).afterPropertiesSet();
	}
}
 
Example #18
Source File: MQHierachy.java    From Thunder with 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 File: CompositeFilterProxy.java    From mPaaS with 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 File: DataJpaApplication.java    From building-microservices with 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
Source File: AbstractHttpRequestFactoryTestCase.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public final void createFactory() throws Exception {
	factory = createRequestFactory();
	if (factory instanceof InitializingBean) {
		((InitializingBean) factory).afterPropertiesSet();
	}
}
 
Example #22
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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
Source File: AsyncExceptionHandlingAsyncTaskExecutor.java    From cola-cloud with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (executor instanceof InitializingBean) {
        InitializingBean bean = (InitializingBean) executor;
        bean.afterPropertiesSet();
    }
}
 
Example #24
Source File: CinemaServiceApplication.java    From Software-Architecture-with-Spring-5.0 with MIT License 5 votes vote down vote up
@Bean
InitializingBean populateDatabase(CinemaRepository movieRepository) {
    return () -> {
        movieRepository.save(new Cinema(1, "Alamo", null));
        movieRepository.save(new Cinema(2, "4DX", null));
    };
}
 
Example #25
Source File: SpringDataDemoApplication.java    From Software-Architecture-with-Spring-5.0 with MIT License 5 votes vote down vote up
@Bean
InitializingBean populateDatabase(CountryRepository countryRepository) {
    return () -> {
        countryRepository.save(new Country(1, "USA"));
        countryRepository.save(new Country(2, "Ecuador"));
    };
}
 
Example #26
Source File: MessagingApplication.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@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 File: EgeriaUIPlatform.java    From egeria with Apache License 2.0 5 votes vote down vote up
@Bean
public InitializingBean getInitialize()
{
    return () -> {
        if (!strictSSL)
        {
            HttpHelper.noStrictSSL();
        }
    };
}
 
Example #28
Source File: OMAGServerPlatform.java    From egeria with 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
Source File: ExceptionHandlingAsyncTaskExecutor.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * 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 File: SpringAwareListener.java    From micronaut-spring with 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;
}