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

The following examples show how to use org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils. 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: BeanFactoryAwareFunctionRegistry.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: DeviceEventProcessor.java    From konker-platform with 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 #3
Source File: TransactionalTestExecutionListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: AsyncExecutionAspectSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: TransactionalTestExecutionListener.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 #6
Source File: TransactionalTestExecutionListener.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 #7
Source File: TransactionAspectSupport.java    From java-technology-stack with 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 #8
Source File: ConverterHelper.java    From konker-platform with 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 #9
Source File: TransactionAspectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: AsyncExecutionAspectSupport.java    From lams with GNU General Public License v2.0 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)
 */
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 #11
Source File: TransactionAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 #12
Source File: BeanMethodQualificationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #13
Source File: BeanMethodQualificationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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
Source File: AsyncExecutionAspectSupport.java    From java-technology-stack with 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 #15
Source File: TransactionAspectSupport.java    From spring-analysis-note with 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 #16
Source File: TransactionAspectSupport.java    From spring-analysis-note with 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 #17
Source File: BeanMethodQualificationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #18
Source File: BeanMethodQualificationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #19
Source File: AsyncExecutionAspectSupport.java    From spring-analysis-note with 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 #20
Source File: AspectJExpressionPointcut.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private boolean matchesBean(String advisedBeanName) {
	return BeanFactoryAnnotationUtils.isQualifierMatch(
			this.expressionPattern::matches, advisedBeanName, beanFactory);
}
 
Example #21
Source File: BaseAutoConfiguration.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
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 #22
Source File: AspectJExpressionPointcut.java    From java-technology-stack with MIT License 4 votes vote down vote up
private boolean matchesBean(String advisedBeanName) {
	return BeanFactoryAnnotationUtils.isQualifierMatch(
			this.expressionPattern::matches, advisedBeanName, beanFactory);
}
 
Example #23
Source File: CacheAspectSupport.java    From java-technology-stack with 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 #24
Source File: CacheAspectSupport.java    From spring-analysis-note with 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 #25
Source File: CacheAspectSupport.java    From lams with 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 File: CacheAspectSupport.java    From spring4-understanding with 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);
}