简体   繁体   中英

Check, if a scoped bean is null

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?

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()

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM