001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.messaging.core; 018 019import org.springframework.beans.BeansException; 020import org.springframework.beans.factory.BeanFactory; 021import org.springframework.beans.factory.BeanFactoryAware; 022import org.springframework.lang.Nullable; 023import org.springframework.messaging.MessageChannel; 024import org.springframework.util.Assert; 025 026/** 027 * An implementation of {@link DestinationResolver} that interprets a destination 028 * name as the bean name of a {@link MessageChannel} and looks up the bean in 029 * the configured {@link BeanFactory}. 030 * 031 * @author Mark Fisher 032 * @since 4.0 033 */ 034public class BeanFactoryMessageChannelDestinationResolver 035 implements DestinationResolver<MessageChannel>, BeanFactoryAware { 036 037 @Nullable 038 private BeanFactory beanFactory; 039 040 041 /** 042 * A default constructor that can be used when the resolver itself is configured 043 * as a Spring bean and will have the {@code BeanFactory} injected as a result 044 * of ing having implemented {@link BeanFactoryAware}. 045 */ 046 public BeanFactoryMessageChannelDestinationResolver() { 047 } 048 049 /** 050 * A constructor that accepts a {@link BeanFactory} useful if instantiating this 051 * resolver manually rather than having it defined as a Spring-managed bean. 052 * @param beanFactory the bean factory to perform lookups against 053 */ 054 public BeanFactoryMessageChannelDestinationResolver(BeanFactory beanFactory) { 055 Assert.notNull(beanFactory, "beanFactory must not be null"); 056 this.beanFactory = beanFactory; 057 } 058 059 060 @Override 061 public void setBeanFactory(BeanFactory beanFactory) { 062 this.beanFactory = beanFactory; 063 } 064 065 066 @Override 067 public MessageChannel resolveDestination(String name) { 068 Assert.state(this.beanFactory != null, "No BeanFactory configured"); 069 try { 070 return this.beanFactory.getBean(name, MessageChannel.class); 071 } 072 catch (BeansException ex) { 073 throw new DestinationResolutionException( 074 "Failed to find MessageChannel bean with name '" + name + "'", ex); 075 } 076 } 077 078}