Skip to content

Instantly share code, notes, and snippets.

@garyrussell
Created December 13, 2013 23:49
Show Gist options
  • Save garyrussell/7953672 to your computer and use it in GitHub Desktop.
Save garyrussell/7953672 to your computer and use it in GitHub Desktop.
Example of how to unwrap a proxied Spring Integration element (in this case a QueueChannel).
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package foo;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.Advised;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.channel.QueueChannel;
/**
* @author Gary Russell
*/
public class Foo {
private QueueChannel channel;
// note you can't use a normal setter, unless you omit the getter - they have to have the same type
public final void setProxyOrChannel(MessageChannel channel) {
this.channel = this.extractTypeIfPossible(channel, QueueChannel.class);
}
public final QueueChannel getChannel() {
return channel;
}
@SuppressWarnings("unchecked")
<T> T extractTypeIfPossible(Object targetObject, Class<T> expectedType) {
if (targetObject == null) {
return null;
}
if (expectedType.isAssignableFrom(targetObject.getClass())) {
return (T) targetObject;
}
if (targetObject instanceof Advised) {
TargetSource targetSource = ((Advised) targetObject).getTargetSource();
if (targetSource == null) {
return null;
}
try {
return extractTypeIfPossible(targetSource.getTarget(), expectedType);
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment