org.springframework.beans.BeansException Java Examples

The following examples show how to use org.springframework.beans.BeansException. 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: Utils.java    From urule with Apache License 2.0 6 votes vote down vote up
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	functionDescriptorMap.clear();
	functionDescriptorLabelMap.clear();
	Collection<FunctionDescriptor> functionDescriptors=applicationContext.getBeansOfType(FunctionDescriptor.class).values();
	for(FunctionDescriptor fun:functionDescriptors){
		if(fun.isDisabled()){
			continue;
		}
		if(functionDescriptorMap.containsKey(fun.getName())){
			throw new RuntimeException("Duplicate function ["+fun.getName()+"]");
		}
		functionDescriptorMap.put(fun.getName(), fun);
		functionDescriptorLabelMap.put(fun.getLabel(), fun);
	}
	debugWriters=applicationContext.getBeansOfType(DebugWriter.class).values();
	Utils.applicationContext=applicationContext;
	new Splash().print();
}
 
Example #2
Source File: DisruptorEventAwareProcessor.java    From disruptor-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
	AccessControlContext acc = null;
	if (System.getSecurityManager() != null && (bean instanceof DisruptorEventPublisherAware )) {
		acc = getAccessControlContext();
	}
	if (acc != null) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			@Override
			public Object run() {
				invokeAwareInterfaces(bean);
				return null;
			}
		}, acc);
	}
	else {
		invokeAwareInterfaces(bean);
	}

	return bean;
}
 
Example #3
Source File: PredictionAlgorithmStore.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
	 this.applicationContext = applicationContext;
	 StringBuilder builder= new StringBuilder("Available algorithms: \n");
	 for (PredictionAlgorithm inc : applicationContext.getBeansOfType(PredictionAlgorithm.class).values()){
		 builder.append('\t');
		 builder.append(inc.getClass());
		 builder.append('\n');
	 }
	 builder.append("Available feature transformers: \n");
	 for(FeatureTransformer f : applicationContext.getBeansOfType(FeatureTransformer.class).values()){
		 builder.append('\t');
		 builder.append(f.getClass());
		 builder.append('\n');			 
	 }
	 logger.info(builder.toString());
        
}
 
Example #4
Source File: DeprecatedBeanWarner.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (isLogEnabled()) {
		String[] beanNames = beanFactory.getBeanDefinitionNames();
		for (String beanName : beanNames) {
			String nameToLookup = beanName;
			if (beanFactory.isFactoryBean(beanName)) {
				nameToLookup = BeanFactory.FACTORY_BEAN_PREFIX + beanName;
			}
			Class<?> beanType = ClassUtils.getUserClass(beanFactory.getType(nameToLookup));
			if (beanType != null && beanType.isAnnotationPresent(Deprecated.class)) {
				BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
				logDeprecatedBean(beanName, beanType, beanDefinition);
			}
		}
	}
}
 
Example #5
Source File: DataRedisContextInitializer.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    Environment env = applicationContext.getEnvironment();
    applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof RedisTemplate) {
                RedisTemplate redisTemplate = (RedisTemplate)bean;
                // do cache
                redisTemplate.opsForValue();
                redisTemplate.opsForList();
                redisTemplate.opsForSet();
                redisTemplate.opsForZSet();
                redisTemplate.opsForGeo();
                redisTemplate.opsForHash();
                redisTemplate.opsForHyperLogLog();
                createProxyHandlers(redisTemplate);
            }
            return bean;
        }
    });
}
 
Example #6
Source File: TurboClientStarter.java    From turbo-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
	if (bean == null) {
		return bean;
	}

	if (bean instanceof TurboClientAware) {
		((TurboClientAware) bean).setTurboClient(turboClient);
	}

	Class<?> clazz = bean.getClass();
	TurboFailover turboFailover = clazz.getAnnotation(TurboFailover.class);

	if (turboFailover == null) {
		return bean;
	}

	if (logger.isInfoEnabled()) {
		logger.info("扫描到Failover实例,重置TurboFailover: " + clazz.getName() + turboFailover);
	}

	turboClient.setFailover(turboFailover.service(), bean);

	return bean;
}
 
Example #7
Source File: AnnotationBean.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
        throws BeansException {
    if (annotationPackage == null || annotationPackage.length() == 0) {
        return;
    }
    if (beanFactory instanceof BeanDefinitionRegistry) {
        try {
            // init scanner
            Class<?> scannerClass = ReflectUtils.forName("org.springframework.context.annotation.ClassPathBeanDefinitionScanner");
            Object scanner = scannerClass.getConstructor(new Class<?>[] {BeanDefinitionRegistry.class, boolean.class}).newInstance(new Object[] {(BeanDefinitionRegistry) beanFactory, true});
            // add filter
            Class<?> filterClass = ReflectUtils.forName("org.springframework.core.type.filter.AnnotationTypeFilter");
            Object filter = filterClass.getConstructor(Class.class).newInstance(Service.class);
            Method addIncludeFilter = scannerClass.getMethod("addIncludeFilter", ReflectUtils.forName("org.springframework.core.type.filter.TypeFilter"));
            addIncludeFilter.invoke(scanner, filter);
            // scan packages
            String[] packages = Constants.COMMA_SPLIT_PATTERN.split(annotationPackage);
            Method scan = scannerClass.getMethod("scan", new Class<?>[]{String[].class});
            scan.invoke(scanner, new Object[] {packages});
        } catch (Throwable e) {
            // spring 2.0
        }
    }
}
 
Example #8
Source File: TaskManager.java    From Taroco-Scheduler with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 封装ScheduledMethodRunnable对象
 */
private ScheduledMethodRunnable buildScheduledRunnable(String targetBean, String targetMethod, String params, String extKeySuffix) {
    Object bean;
    ScheduledMethodRunnable scheduledMethodRunnable;
    final String scheduleKey = ScheduleUtil.buildScheduleKey(targetBean, targetMethod, extKeySuffix);
    try {
        bean = applicationContext.getBean(targetBean);
    } catch (BeansException e) {
        zkClient.getTaskGenerator().getScheduleTask().saveRunningInfo(scheduleKey, ScheduleServer.getInstance().getUuid(), e.getLocalizedMessage());
        log.error("启动动态任务失败: {}, 失败原因: {}", scheduleKey, e.getLocalizedMessage());
        log.error(e.getLocalizedMessage(), e);
        return null;
    }
    scheduledMethodRunnable = buildScheduledRunnable(bean, targetMethod, params, extKeySuffix, scheduleKey);
    return scheduledMethodRunnable;
}
 
Example #9
Source File: BeanValidationPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
	if (!this.afterInitialization) {
		doValidate(bean);
	}
	return bean;
}
 
Example #10
Source File: AbstractBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a 'merged' BeanDefinition for the given bean name,
 * merging a child bean definition with its parent if necessary.
 * <p>This {@code getMergedBeanDefinition} considers bean definition
 * in ancestors as well.
 * @param name the name of the bean to retrieve the merged definition for
 * (may be an alias)
 * @return a (potentially merged) RootBeanDefinition for the given bean
 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
 * @throws BeanDefinitionStoreException in case of an invalid bean definition
 */
@Override
public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
	String beanName = transformedBeanName(name);

	// Efficiently check whether bean definition exists in this factory.
	if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
		return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
	}
	// Resolve merged bean definition locally.
	return getMergedLocalBeanDefinition(beanName);
}
 
Example #11
Source File: SQLErrorCodesFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of the {@link SQLErrorCodesFactory} class.
 * <p>Not public to enforce Singleton design pattern. Would be private
 * except to allow testing via overriding the
 * {@link #loadResource(String)} method.
 * <p><b>Do not subclass in application code.</b>
 * @see #loadResource(String)
 */
protected SQLErrorCodesFactory() {
	Map<String, SQLErrorCodes> errorCodes;

	try {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		lbf.setBeanClassLoader(getClass().getClassLoader());
		XmlBeanDefinitionReader bdr = new XmlBeanDefinitionReader(lbf);

		// Load default SQL error codes.
		Resource resource = loadResource(SQL_ERROR_CODE_DEFAULT_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
		}
		else {
			logger.warn("Default sql-error-codes.xml not found (should be included in spring.jar)");
		}

		// Load custom SQL error codes, overriding defaults.
		resource = loadResource(SQL_ERROR_CODE_OVERRIDE_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
			logger.info("Found custom sql-error-codes.xml file at the root of the classpath");
		}

		// Check all beans of type SQLErrorCodes.
		errorCodes = lbf.getBeansOfType(SQLErrorCodes.class, true, false);
		if (logger.isInfoEnabled()) {
			logger.info("SQLErrorCodes loaded: " + errorCodes.keySet());
		}
	}
	catch (BeansException ex) {
		logger.warn("Error loading SQL error codes from config file", ex);
		errorCodes = Collections.emptyMap();
	}

	this.errorCodesMap = errorCodes;
}
 
Example #12
Source File: VnfmManager.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@Override
@Async
public Future<Void> release(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord)
    throws NotFoundException, BadFormatException, ExecutionException, InterruptedException {
  VnfmManagerEndpoint endpoint = generator.getVnfm(virtualNetworkFunctionRecord.getEndpoint());
  if (endpoint == null) {
    throw new NotFoundException(
        "VnfManager of type "
            + virtualNetworkFunctionRecord.getType()
            + " (endpoint = "
            + virtualNetworkFunctionRecord.getEndpoint()
            + ") is not registered");
  }

  OrVnfmGenericMessage orVnfmGenericMessage =
      new OrVnfmGenericMessage(virtualNetworkFunctionRecord, Action.RELEASE_RESOURCES);
  VnfmSender vnfmSender;
  try {

    vnfmSender = generator.getVnfmSender(endpoint.getEndpointType());
  } catch (BeansException e) {
    throw new NotFoundException(e);
  }

  vnfStateHandler.executeAction(vnfmSender.sendCommand(orVnfmGenericMessage, endpoint));
  return new AsyncResult<>(null);
}
 
Example #13
Source File: ProfillInterceptorTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void プロフィルが設定されていない場合はBeanFactoryから型一致で検索する() throws Exception {
    interceptor.setBeanFactory(new BeanFactoryStub() {
        @Override public <T> T getBean(Class<T> requiredType) throws BeansException {
            return requiredType.cast(new Profill());
        }
    });
    interceptor.afterPropertiesSet();
    assertThat(interceptor.getProfill(), is(notNullValue()));
}
 
Example #14
Source File: CustomizeBeanPostProcessor.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if("calculateService".equals(beanName)) {
        Utils.printTrack("do postProcess before initialization");
        CalculateService calculateService = (CalculateService)bean;
        calculateService.setServiceDesc("desc from " + this.getClass().getSimpleName());
    }
    return bean;
}
 
Example #15
Source File: QConfigPropertySourceAnnotationProcessor.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    super.setBeanFactory(beanFactory);
    if (beanFactory instanceof ConfigurableListableBeanFactory) {
        filenameToPropsMap = loadQConfigFilesInAnnotation((ConfigurableListableBeanFactory) beanFactory, beanClassLoader);
    }
}
 
Example #16
Source File: BeanFactoryAnnotationUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Retrieve all bean of type {@code T} from the given {@code BeanFactory} declaring a
 * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given
 * qualifier, or having a bean name matching the given qualifier.
 * @param beanFactory the factory to get the target beans from (also searching ancestors)
 * @param beanType the type of beans to retrieve
 * @param qualifier the qualifier for selecting among all type matches
 * @return the matching beans of type {@code T}
 * @throws BeansException if any of the matching beans could not be created
 * @since 5.1.1
 * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
 */
public static <T> Map<String, T> qualifiedBeansOfType(
		ListableBeanFactory beanFactory, Class<T> beanType, String qualifier) throws BeansException {

	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, beanType);
	Map<String, T> result = new LinkedHashMap<>(4);
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier::equals, beanName, beanFactory)) {
			result.put(beanName, beanFactory.getBean(beanName, beanType));
		}
	}
	return result;
}
 
Example #17
Source File: ApolloProcessor.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
    throws BeansException {
  Class clazz = bean.getClass();
  for (Field field : findAllField(clazz)) {
    processField(bean, beanName, field);
  }
  for (Method method : findAllMethod(clazz)) {
    processMethod(bean, beanName, method);
  }
  return bean;
}
 
Example #18
Source File: XmlViewResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Initialize the view bean factory from the XML file.
 * Synchronized because of access by parallel threads.
 * @throws BeansException in case of initialization errors
 */
protected synchronized BeanFactory initFactory() throws BeansException {
	if (this.cachedFactory != null) {
		return this.cachedFactory;
	}

	ApplicationContext applicationContext = obtainApplicationContext();

	Resource actualLocation = this.location;
	if (actualLocation == null) {
		actualLocation = applicationContext.getResource(DEFAULT_LOCATION);
	}

	// Create child ApplicationContext for views.
	GenericWebApplicationContext factory = new GenericWebApplicationContext();
	factory.setParent(applicationContext);
	factory.setServletContext(getServletContext());

	// Load XML resource with context-aware entity resolver.
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
	reader.setEnvironment(applicationContext.getEnvironment());
	reader.setEntityResolver(new ResourceEntityResolver(applicationContext));
	reader.loadBeanDefinitions(actualLocation);

	factory.refresh();

	if (isCache()) {
		this.cachedFactory = factory;
	}
	return factory;
}
 
Example #19
Source File: GemFireDebugConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
public BeanPostProcessor gemfireCacheSslConfigurationBeanPostProcessor() {

	return new BeanPostProcessor() {

		@Nullable @Override
		public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

			Optional.ofNullable(bean)
				.filter(GemFireCache.class::isInstance)
				.map(GemFireCache.class::cast)
				.map(GemFireCache::getDistributedSystem)
				.filter(InternalDistributedSystem.class::isInstance)
				.map(InternalDistributedSystem.class::cast)
				.map(InternalDistributedSystem::getConfig)
				.ifPresent(distributionConfig -> {

					SecurableCommunicationChannel[] securableCommunicationChannels =
						ArrayUtils.nullSafeArray(distributionConfig.getSecurableCommunicationChannels(),
							SecurableCommunicationChannel.class);

					logger.error("SECURABLE COMMUNICATION CHANNELS {}",
						Arrays.toString(securableCommunicationChannels));

					Arrays.stream(securableCommunicationChannels).forEach(securableCommunicationChannel -> {

						SSLConfig sslConfig = SSLConfigurationFactory
							.getSSLConfigForComponent(distributionConfig, securableCommunicationChannel);

						logger.error("{} SSL CONFIGURATION [{}]", securableCommunicationChannel.name(), sslConfig);
					});
				});

			return bean;
		}
	};
}
 
Example #20
Source File: StaticListableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
		throws BeansException {

	Map<String, Object> results = new LinkedHashMap<String, Object>();
	for (String beanName : this.beans.keySet()) {
		if (findAnnotationOnBean(beanName, annotationType) != null) {
			results.put(beanName, getBean(beanName));
		}
	}
	return results;
}
 
Example #21
Source File: SakaiContextLoader.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Spring allows a parent ApplicationContext to be set during the creation of a new ApplicationContext
 *
 * Sakai sets the SakaiApplicationContext as the parent which managed by the ComponentManager
 * 
 * @param servletContext (not used)
 * @return the shared SakaiApplicationContext
 */
@Override
protected ApplicationContext loadParentContext(ServletContext servletContext) throws BeansException
{
	// get the component manager (we know it's a SpringCompMgr) and from that the shared AC
	ConfigurableApplicationContext sharedAc = ((SpringCompMgr) ComponentManager.getInstance()).getApplicationContext();

	return sharedAc;
}
 
Example #22
Source File: ChromeDriverFactory.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Override
public ChromeDriver getObject() throws BeansException {
	if (properties.getChrome().isEnabled()) {
		try {
			return new ChromeDriver(chromeDriverService);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			// swallow the exception
		}
	}
	return null;
}
 
Example #23
Source File: MyAwareService.java    From journaldev with MIT License 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext ctx)
		throws BeansException {
	System.out.println("setApplicationContext called");
	System.out.println("setApplicationContext:: Bean Definition Names="
			+ Arrays.toString(ctx.getBeanDefinitionNames()));
}
 
Example #24
Source File: SpringLifeCycleProcessor.java    From Java-Interview with MIT License 5 votes vote down vote up
/**
 * 预初始化 初始化之前调用
 * @param bean
 * @param beanName
 * @return
 * @throws BeansException
 */
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if ("annotationBean".equals(beanName)){
        LOGGER.info("SpringLifeCycleProcessor start beanName={}",beanName);
    }
    return bean;
}
 
Example #25
Source File: ConfigurationDtoPostProcessor.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void checkLayerTree(ClientMapInfo map) throws BeansException {
	// if the map contains a layer tree, verify that the layers are part of the map
	ClientLayerTreeInfo layerTree = map.getLayerTree();
	if (null != layerTree) {
		checkTreeNode(map, layerTree.getTreeNode());
	}
}
 
Example #26
Source File: StaticApplicationContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Register a singleton bean with the underlying bean factory.
 * <p>For more advanced needs, register with the underlying BeanFactory directly.
 * @see #getDefaultListableBeanFactory
 */
public void registerSingleton(String name, Class<?> clazz, MutablePropertyValues pvs) throws BeansException {
	GenericBeanDefinition bd = new GenericBeanDefinition();
	bd.setBeanClass(clazz);
	bd.setPropertyValues(pvs);
	getDefaultListableBeanFactory().registerBeanDefinition(name, bd);
}
 
Example #27
Source File: ContextHierarchyDirtiesContextTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	ContextHierarchyDirtiesContextTests.context = applicationContext;
	ContextHierarchyDirtiesContextTests.baz = applicationContext.getBean("bean", String.class);
	ContextHierarchyDirtiesContextTests.bar = applicationContext.getParent().getBean("bean", String.class);
	ContextHierarchyDirtiesContextTests.foo = applicationContext.getParent().getParent().getBean("bean", String.class);
}
 
Example #28
Source File: BeanUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Get property value null if none
 * @param bean beam
 * @param name name
 * @return the property value
 */
public static Object getProperty(Object bean, String name) {
	try {
		BeanWrapper wrapper = new BeanWrapperImpl(bean);
		return wrapper.getPropertyValue(name);
	} catch (BeansException be) {
		log.error(be);
		return null;
	}
}
 
Example #29
Source File: AbstractBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a merged RootBeanDefinition, traversing the parent bean definition
 * if the specified bean corresponds to a child bean definition.
 * @param beanName the name of the bean to retrieve the merged definition for
 * @return a (potentially merged) RootBeanDefinition for the given bean
 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
 * @throws BeanDefinitionStoreException in case of an invalid bean definition
 */
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
	// Quick check on the concurrent map first, with minimal locking.
	RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
	if (mbd != null) {
		return mbd;
	}
	return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
 
Example #30
Source File: OrganizationalAuthorizationAutoConfiguration.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof PersonnelAuthenticationSupplier) {
        PersonnelAuthenticationHolder.addSupplier(((PersonnelAuthenticationSupplier) bean));
    }
    return bean;
}