Reputation: 621
In my Java-Configuration in Spring I have a bean, that is annotated as follows:
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Object foo() { ... }
This method sometimes returns a null (if there is nothing to instanciate). In my code, I would like to check for this case like:
@Inject
Object foo
if (foo != null)
foo.be_wise();
But this does not work, because foo is proxied and, hence, is never null! So, the only way to check for the null I could find is to trigger the NullPointerException like this:
try
{
foo.dont_be_wise();
}
catch (NullPointerException e)
{
be_wise();
}
I do not like that, because throwing exceptions is costly!
Is there another way to check the proxied bean for null?
Upvotes: 0
Views: 1902
Reputation: 7147
Support for unwrapping proxies has been added to the spring-test module (Spring 4.2.4). See the related commit https://github.com/spring-projects/spring-framework/commit/efe3a35da871a7ef34148dfb65d6a96cac1fccb9
Slightly modified example (see also AopUtils):
if (AopUtils.isAopProxy(myBean) && (myBean instanceof Advised)) {
MyFoo target ((Advised) myBean).getTargetSource().getTarget();
if (target != null) {
// ...
}
}
Although this is a way to go there are alternative (and probably more elegant ways) to solve the problem:
Null Object
Introducing a NoOp implementation of your interface abstracts the null-ckecks away from your client code. See Null Object Design Pattern.
In this case your @Bean
method would never return null
.
Conditional Bean Registration
Since Spring 4.0 beans can be instantiated on a @Conditional basis. Depending on your use-case this could be an option. See Conditionally include @Bean methods.
Upvotes: 2
Reputation: 1099
This might work for retrieving the proxied instance. In Spring 4.2.4, this works for @Autowired
-injected beans, which I think is basically the same thing.
((org.springframework.aop.framework.Advised) foo).getTargetSource().getTarget()
Upvotes: 0