类org.springframework.beans.BeansException源码实例Demo

下面列出了怎么用org.springframework.beans.BeansException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: seldon-server   文件: PredictionAlgorithmStore.java
@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());
        
}
 
@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;
}
 
@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;
        }
    });
}
 
源代码4 项目: dubbox-hystrix   文件: AnnotationBean.java
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
        }
    }
}
 
源代码5 项目: Taroco-Scheduler   文件: TaskManager.java
/**
 * 封装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;
}
 
源代码6 项目: turbo-rpc   文件: TurboClientStarter.java
@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;
}
 
@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);
			}
		}
	}
}
 
源代码8 项目: urule   文件: Utils.java
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();
}
 
源代码9 项目: apollo   文件: ApolloProcessor.java
@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;
}
 
/**
 * 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;
}
 
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    super.setBeanFactory(beanFactory);
    if (beanFactory instanceof ConfigurableListableBeanFactory) {
        filenameToPropsMap = loadQConfigFilesInAnnotation((ConfigurableListableBeanFactory) beanFactory, beanClassLoader);
    }
}
 
源代码12 项目: NFVO   文件: VnfmManager.java
@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);
}
 
/**
 * 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;
}
 
源代码14 项目: blog_demos   文件: CustomizeBeanPostProcessor.java
@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;
}
 
源代码15 项目: sakai   文件: SakaiContextLoader.java
/**
 * 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;
}
 
@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;
}
 
源代码17 项目: journaldev   文件: MyAwareService.java
@Override
public void setApplicationContext(ApplicationContext ctx)
		throws BeansException {
	System.out.println("setApplicationContext called");
	System.out.println("setApplicationContext:: Bean Definition Names="
			+ Arrays.toString(ctx.getBeanDefinitionNames()));
}
 
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());
	}
}
 
@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);
}
 
/**
 * 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));
}
 
@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;
		}
	};
}
 
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof PersonnelAuthenticationSupplier) {
        PersonnelAuthenticationHolder.addSupplier(((PersonnelAuthenticationSupplier) bean));
    }
    return bean;
}
 
源代码23 项目: jdal   文件: BeanUtils.java
/**
 * 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;
	}
}
 
/**
 * 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);
}
 
源代码25 项目: Java-Interview   文件: SpringLifeCycleProcessor.java
/**
 * 预初始化 初始化之前调用
 * @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;
}
 
@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;
}
 
源代码27 项目: sinavi-jfw   文件: ProfillInterceptorTest.java
@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()));
}
 
源代码28 项目: java-technology-stack   文件: XmlViewResolver.java
/**
 * 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;
}
 
源代码29 项目: lams   文件: AbstractBeanFactory.java
/**
 * 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);
}
 
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
	if (!this.afterInitialization) {
		doValidate(bean);
	}
	return bean;
}
 
 类方法
 同包方法