Java Code Examples for org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils

The following examples show how to use org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils. 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 check out the related API usage on the sidebar.
Example 1
/**
 * Get the {@linkplain PlatformTransactionManager transaction manager} to use
 * for the supplied {@linkplain TestContext test context} and {@code qualifier}.
 * <p>Delegates to {@link #getTransactionManager(TestContext)} if the
 * supplied {@code qualifier} is {@code null} or empty.
 * @param testContext the test context for which the transaction manager
 * should be retrieved
 * @param qualifier the qualifier for selecting between multiple bean matches;
 * may be {@code null} or empty
 * @return the transaction manager to use, or {@code null} if not found
 * @throws BeansException if an error occurs while retrieving the transaction manager
 * @see #getTransactionManager(TestContext)
 */
@Nullable
protected PlatformTransactionManager getTransactionManager(TestContext testContext, @Nullable String qualifier) {
	// Look up by type and qualifier from @Transactional
	if (StringUtils.hasText(qualifier)) {
		try {
			// Use autowire-capable factory in order to support extended qualifier matching
			// (only exposed on the internal BeanFactory, not on the ApplicationContext).
			BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();

			return BeanFactoryAnnotationUtils.qualifiedBeanOfType(bf, PlatformTransactionManager.class, qualifier);
		}
		catch (RuntimeException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn(String.format(
						"Caught exception while retrieving transaction manager with qualifier '%s' for test context %s",
						qualifier, testContext), ex);
			}
			throw ex;
		}
	}

	// else
	return getTransactionManager(testContext);
}
 
Example 2
/**
 * Get the {@linkplain PlatformTransactionManager transaction manager} to use
 * for the supplied {@linkplain TestContext test context} and {@code qualifier}.
 * <p>Delegates to {@link #getTransactionManager(TestContext)} if the
 * supplied {@code qualifier} is {@code null} or empty.
 * @param testContext the test context for which the transaction manager
 * should be retrieved
 * @param qualifier the qualifier for selecting between multiple bean matches;
 * may be {@code null} or empty
 * @return the transaction manager to use, or {@code null} if not found
 * @throws BeansException if an error occurs while retrieving the transaction manager
 * @see #getTransactionManager(TestContext)
 */
@Nullable
protected PlatformTransactionManager getTransactionManager(TestContext testContext, @Nullable String qualifier) {
	// Look up by type and qualifier from @Transactional
	if (StringUtils.hasText(qualifier)) {
		try {
			// Use autowire-capable factory in order to support extended qualifier matching
			// (only exposed on the internal BeanFactory, not on the ApplicationContext).
			BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();

			return BeanFactoryAnnotationUtils.qualifiedBeanOfType(bf, PlatformTransactionManager.class, qualifier);
		}
		catch (RuntimeException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn(String.format(
						"Caught exception while retrieving transaction manager with qualifier '%s' for test context %s",
						qualifier, testContext), ex);
			}
			throw ex;
		}
	}

	// else
	return getTransactionManager(testContext);
}
 
Example 3
/**
 * Determine the specific executor to use when executing the given method.
 * Should preferably return an {@link AsyncListenableTaskExecutor} implementation.
 * @return the executor to use (or {@code null}, but just if no default executor has been set)
 */
protected AsyncTaskExecutor determineAsyncExecutor(Method method) {
	AsyncTaskExecutor executor = this.executors.get(method);
	if (executor == null) {
		Executor executorToUse = this.defaultExecutor;
		String qualifier = getExecutorQualifier(method);
		if (StringUtils.hasLength(qualifier)) {
			if (this.beanFactory == null) {
				throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() +
						" to access qualified executor '" + qualifier + "'");
			}
			executorToUse = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
					this.beanFactory, Executor.class, qualifier);
		}
		else if (executorToUse == null) {
			return null;
		}
		executor = (executorToUse instanceof AsyncListenableTaskExecutor ?
				(AsyncListenableTaskExecutor) executorToUse : new TaskExecutorAdapter(executorToUse));
		this.executors.put(method, executor);
	}
	return executor;
}
 
Example 4
/**
 * Get the {@linkplain PlatformTransactionManager transaction manager} to use
 * for the supplied {@linkplain TestContext test context} and {@code qualifier}.
 * <p>Delegates to {@link #getTransactionManager(TestContext)} if the
 * supplied {@code qualifier} is {@code null} or empty.
 * @param testContext the test context for which the transaction manager
 * should be retrieved
 * @param qualifier the qualifier for selecting between multiple bean matches;
 * may be {@code null} or empty
 * @return the transaction manager to use, or {@code null} if not found
 * @throws BeansException if an error occurs while retrieving the transaction manager
 * @see #getTransactionManager(TestContext)
 */
protected PlatformTransactionManager getTransactionManager(TestContext testContext, String qualifier) {
	// look up by type and qualifier from @Transactional
	if (StringUtils.hasText(qualifier)) {
		try {
			// Use autowire-capable factory in order to support extended qualifier
			// matching (only exposed on the internal BeanFactory, not on the
			// ApplicationContext).
			BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();

			return BeanFactoryAnnotationUtils.qualifiedBeanOfType(bf, PlatformTransactionManager.class, qualifier);
		}
		catch (RuntimeException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn(
					String.format(
						"Caught exception while retrieving transaction manager with qualifier '%s' for test context %s",
						qualifier, testContext), ex);
			}
			throw ex;
		}
	}

	// else
	return getTransactionManager(testContext);
}
 
Example 5
Source Project: konker-platform   Source File: DeviceEventProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private String getJsonPayload(Device device, byte[] payloadBytes) throws BusinessException {

        DeviceModel.ContentType contentType = device.getDeviceModel().getContentType();
        if (contentType == null) {
            contentType = DeviceModel.ContentType.APPLICATION_JSON;
        }

        JsonConverter jsonConverter = BeanFactoryAnnotationUtils.qualifiedBeanOfType(beans, JsonConverter.class, contentType.getValue());
        ServiceResponse<String> jsonConverterResponse = jsonConverter.toJson(payloadBytes);

        if (jsonConverterResponse.isOk()) {
            return jsonConverterResponse.getResult();
        } else {
            throw new BusinessException(Messages.INVALID_PAYLOAD.getCode());
        }

    }
 
Example 6
@Override
Object locateFunction(String name) {
	Object function = super.locateFunction(name);
	if (function == null) {
		try {
			function = BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.applicationContext.getBeanFactory(), Object.class, name);
		}
		catch (Exception e) {
			// ignore
		}
	}
	if (function == null && this.applicationContext.containsBean(name)) {
		function = this.applicationContext.getBean(name);
	}

	if (function != null && this.notFunction(function.getClass())
		&& this.applicationContext
		.containsBean(name + FunctionRegistration.REGISTRATION_NAME_SUFFIX)) { // e.g., Kotlin lambdas
		function = this.applicationContext
			.getBean(name + FunctionRegistration.REGISTRATION_NAME_SUFFIX, FunctionRegistration.class);
	}
	return function;
}
 
Example 7
Source Project: spring-analysis-note   Source File: AsyncExecutionAspectSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Retrieve a target executor for the given qualifier.
 * @param qualifier the qualifier to resolve
 * @return the target executor, or {@code null} if none available
 * @since 4.2.6
 * @see #getExecutorQualifier(Method)
 */
@Nullable
protected Executor findQualifiedExecutor(@Nullable BeanFactory beanFactory, String qualifier) {
	if (beanFactory == null) {
		throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() +
				" to access qualified executor '" + qualifier + "'");
	}
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, Executor.class, qualifier);
}
 
Example 8
@Test
public void testCustomWithLazyResolution() {
	AnnotationConfigApplicationContext ctx =
			new AnnotationConfigApplicationContext(CustomConfig.class, CustomPojo.class);
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"),
			"testBean2", ctx.getDefaultListableBeanFactory()));
	CustomPojo pojo = ctx.getBean(CustomPojo.class);
	assertThat(pojo.testBean.getName(), equalTo("interesting"));
	TestBean testBean2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
			ctx.getDefaultListableBeanFactory(), TestBean.class, "boring");
	assertThat(testBean2.getName(), equalTo("boring"));
}
 
Example 9
@Test
public void testCustomWithEarlyResolution() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomConfig.class, CustomPojo.class);
	ctx.refresh();
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	ctx.getBean("testBean2");
	assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"),
			"testBean2", ctx.getDefaultListableBeanFactory()));
	CustomPojo pojo = ctx.getBean(CustomPojo.class);
	assertThat(pojo.testBean.getName(), equalTo("interesting"));
}
 
Example 10
Source Project: spring-analysis-note   Source File: TransactionAspectSupport.java    License: MIT License 5 votes vote down vote up
private PlatformTransactionManager determineQualifiedTransactionManager(BeanFactory beanFactory, String qualifier) {
	PlatformTransactionManager txManager = asPlatformTransactionManager(this.transactionManagerCache.get(qualifier));
	if (txManager == null) {
		txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
				beanFactory, PlatformTransactionManager.class, qualifier);
		this.transactionManagerCache.putIfAbsent(qualifier, txManager);
	}
	return txManager;
}
 
Example 11
Source Project: spring-analysis-note   Source File: TransactionAspectSupport.java    License: MIT License 5 votes vote down vote up
private ReactiveTransactionManager determineQualifiedTransactionManager(BeanFactory beanFactory, String qualifier) {
	ReactiveTransactionManager txManager = asReactiveTransactionManager(transactionManagerCache.get(qualifier));
	if (txManager == null) {
		txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
				beanFactory, ReactiveTransactionManager.class, qualifier);
		transactionManagerCache.putIfAbsent(qualifier, txManager);
	}
	return txManager;
}
 
Example 12
/**
 * Retrieve a target executor for the given qualifier.
 * @param qualifier the qualifier to resolve
 * @return the target executor, or {@code null} if none available
 * @since 4.2.6
 * @see #getExecutorQualifier(Method)
 */
@Nullable
protected Executor findQualifiedExecutor(@Nullable BeanFactory beanFactory, String qualifier) {
	if (beanFactory == null) {
		throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() +
				" to access qualified executor '" + qualifier + "'");
	}
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, Executor.class, qualifier);
}
 
Example 13
@Test
public void testCustomWithLazyResolution() {
	AnnotationConfigApplicationContext ctx =
			new AnnotationConfigApplicationContext(CustomConfig.class, CustomPojo.class);
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"),
			"testBean2", ctx.getDefaultListableBeanFactory()));
	CustomPojo pojo = ctx.getBean(CustomPojo.class);
	assertThat(pojo.testBean.getName(), equalTo("interesting"));
	TestBean testBean2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
			ctx.getDefaultListableBeanFactory(), TestBean.class, "boring");
	assertThat(testBean2.getName(), equalTo("boring"));
}
 
Example 14
@Test
public void testCustomWithEarlyResolution() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomConfig.class, CustomPojo.class);
	ctx.refresh();
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean1"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	ctx.getBean("testBean2");
	assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"),
			"testBean2", ctx.getDefaultListableBeanFactory()));
	CustomPojo pojo = ctx.getBean(CustomPojo.class);
	assertThat(pojo.testBean.getName(), equalTo("interesting"));
}
 
Example 15
Source Project: java-technology-stack   Source File: TransactionAspectSupport.java    License: MIT License 5 votes vote down vote up
private PlatformTransactionManager determineQualifiedTransactionManager(BeanFactory beanFactory, String qualifier) {
	PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
	if (txManager == null) {
		txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
				beanFactory, PlatformTransactionManager.class, qualifier);
		this.transactionManagerCache.putIfAbsent(qualifier, txManager);
	}
	return txManager;
}
 
Example 16
private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) {
	PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
	if (txManager == null) {
		txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
				this.beanFactory, PlatformTransactionManager.class, qualifier);
		this.transactionManagerCache.putIfAbsent(qualifier, txManager);
	}
	return txManager;
}
 
Example 17
/**
 * Retrieve a target executor for the given qualifier.
 * @param qualifier the qualifier to resolve
 * @return the target executor, or {@code null} if none available
 * @since 4.2.6
 * @see #getExecutorQualifier(Method)
 */
protected Executor findQualifiedExecutor(BeanFactory beanFactory, String qualifier) {
	if (beanFactory == null) {
		throw new IllegalStateException("BeanFactory must be set on " + getClass().getSimpleName() +
				" to access qualified executor '" + qualifier + "'");
	}
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(beanFactory, Executor.class, qualifier);
}
 
Example 18
private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) {
	PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
	if (txManager == null) {
		txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
				this.beanFactory, PlatformTransactionManager.class, qualifier);
		this.transactionManagerCache.putIfAbsent(qualifier, txManager);
	}
	return txManager;
}
 
Example 19
Source Project: konker-platform   Source File: ConverterHelper.java    License: Apache License 2.0 5 votes vote down vote up
public ServiceResponse<byte[]> getJsonPayload(Device device, String payloadJson) {

        DeviceModel.ContentType contentType = DeviceModel.ContentType.APPLICATION_JSON;
        if (device.getDeviceModel() != null &&
                device.getDeviceModel().getContentType() != null) {
            contentType = device.getDeviceModel().getContentType();
        }

        JsonConverter jsonConverter = BeanFactoryAnnotationUtils.qualifiedBeanOfType(beans, JsonConverter.class, contentType.getValue());
        ServiceResponse<byte[]> jsonConverterResponse = jsonConverter.fromJson(payloadJson);

        return jsonConverterResponse;

    }
 
Example 20
Source Project: spring-analysis-note   Source File: AspectJExpressionPointcut.java    License: MIT License 4 votes vote down vote up
private boolean matchesBean(String advisedBeanName) {
	return BeanFactoryAnnotationUtils.isQualifierMatch(
			this.expressionPattern::matches, advisedBeanName, beanFactory);
}
 
Example 21
Source Project: java-technology-stack   Source File: AspectJExpressionPointcut.java    License: MIT License 4 votes vote down vote up
private boolean matchesBean(String advisedBeanName) {
	return BeanFactoryAnnotationUtils.isQualifierMatch(
			this.expressionPattern::matches, advisedBeanName, beanFactory);
}
 
Example 22
private <T> T findQualifiedBeanByType(Class<? extends T> type, String qualifierValue, Class<? extends Annotation> qualifierType) {
    final NoSuchBeanDefinitionException noSuchBeanDefinitionException = new NoSuchBeanDefinitionException(qualifierValue, "No matching " + type.getSimpleName() +
            " bean found for qualifier " + qualifierValue + " of type " + qualifierType.getSimpleName() + " !");
    try {

        if (StringUtils.isEmpty(qualifierValue)) {
            if (qualifierType.equals(Qualifier.class)) {
                return Optional.of(
                        context.getBean(type))
                        .orElseThrow(() -> noSuchBeanDefinitionException);
            }
            return context.getBean(
                    Arrays.stream(context.getBeanNamesForAnnotation(qualifierType))
                            .filter(beanName -> type.isInstance(context.getBean(beanName)))
                            .findFirst()
                            .orElseThrow(() -> noSuchBeanDefinitionException),
                    type);
        }

        return BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(), type, qualifierValue);
    } catch (NoSuchBeanDefinitionException noBeanException) {
        ConfigurableListableBeanFactory factory = context.getBeanFactory();

        for (String name : factory.getBeanDefinitionNames()) {
            BeanDefinition bd = factory.getBeanDefinition(name);

            if (bd.getSource() instanceof StandardMethodMetadata) {
                StandardMethodMetadata metadata = (StandardMethodMetadata) bd.getSource();

                if (metadata.getReturnTypeName().equals(type.getName())) {
                    Map<String, Object> attributes = metadata.getAnnotationAttributes(qualifierType.getName());
                    if (null != attributes) {
                        if (qualifierType.equals(Qualifier.class)) {
                            if (qualifierValue.equals(attributes.get("value"))) {
                                return context.getBean(name, type);
                            }
                        }
                        return context.getBean(name, type);
                    }
                }
            }
        }

        throw noSuchBeanDefinitionException;
    }
}
 
Example 23
Source Project: spring-analysis-note   Source File: CacheAspectSupport.java    License: MIT License 3 votes vote down vote up
/**
 * Return a bean with the specified name and type. Used to resolve services that
 * are referenced by name in a {@link CacheOperation}.
 * @param beanName the name of the bean, as defined by the operation
 * @param expectedType type for the bean
 * @return the bean matching that name
 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException if such bean does not exist
 * @see CacheOperation#getKeyGenerator()
 * @see CacheOperation#getCacheManager()
 * @see CacheOperation#getCacheResolver()
 */
protected <T> T getBean(String beanName, Class<T> expectedType) {
	if (this.beanFactory == null) {
		throw new IllegalStateException(
				"BeanFactory must be set on cache aspect for " + expectedType.getSimpleName() + " retrieval");
	}
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.beanFactory, expectedType, beanName);
}
 
Example 24
Source Project: java-technology-stack   Source File: CacheAspectSupport.java    License: MIT License 3 votes vote down vote up
/**
 * Return a bean with the specified name and type. Used to resolve services that
 * are referenced by name in a {@link CacheOperation}.
 * @param beanName the name of the bean, as defined by the operation
 * @param expectedType type for the bean
 * @return the bean matching that name
 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException if such bean does not exist
 * @see CacheOperation#keyGenerator
 * @see CacheOperation#cacheManager
 * @see CacheOperation#cacheResolver
 */
protected <T> T getBean(String beanName, Class<T> expectedType) {
	if (this.beanFactory == null) {
		throw new IllegalStateException(
				"BeanFactory must be set on cache aspect for " + expectedType.getSimpleName() + " retrieval");
	}
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.beanFactory, expectedType, beanName);
}
 
Example 25
Source Project: lams   Source File: CacheAspectSupport.java    License: GNU General Public License v2.0 2 votes vote down vote up
/**
 * Return a bean with the specified name and type. Used to resolve services that
 * are referenced by name in a {@link CacheOperation}.
 * @param beanName the name of the bean, as defined by the operation
 * @param expectedType type for the bean
 * @return the bean matching that name
 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException if such bean does not exist
 * @see CacheOperation#keyGenerator
 * @see CacheOperation#cacheManager
 * @see CacheOperation#cacheResolver
 */
protected <T> T getBean(String beanName, Class<T> expectedType) {
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.beanFactory, expectedType, beanName);
}
 
Example 26
Source Project: spring4-understanding   Source File: CacheAspectSupport.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return a bean with the specified name and type. Used to resolve services that
 * are referenced by name in a {@link CacheOperation}.
 * @param beanName the name of the bean, as defined by the operation
 * @param expectedType type type for the bean
 * @return the bean matching that name
 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException if such bean does not exist
 * @see CacheOperation#keyGenerator
 * @see CacheOperation#cacheManager
 * @see CacheOperation#cacheResolver
 */
protected <T> T getBean(String beanName, Class<T> expectedType) {
	return BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.applicationContext, expectedType, beanName);
}