Can @Inject be made optional in JSR 330 (like @Autowire(required=false)?

Eric B. picture Eric B. · Oct 21, 2013 · Viewed 14.5k times · Source

Spring's @Autowire can be configured such that Spring will not throw an error if no matching autowire candidates are found: @Autowire(required=false)

Is there an equivalent JSR-330 annotation? @Inject always fails if there is no matching candidate. Is there any way I can use @Inject but not have the framework fail if no matching types are found? I haven't been able to find any documentation to that extent.

Answer

Utku Özdemir picture Utku Özdemir · Mar 15, 2016

You can use java.util.Optional. If you are using Java 8 and your Spring version is 4.1 or above (see here), instead of

@Autowired(required = false)
private SomeBean someBean;

You can just use java.util.Optional class that came with Java 8. Use it like:

@Inject
private Optional<SomeBean> someBean;

This instance will never be null, and you can use it like:

if (someBean.isPresent()) {
   // do your thing
}

This way you can also do constructor injection, with some beans required and some beans optional, gives great flexibility.

Note: Unfortunately Spring does not support Guava's com.google.common.base.Optional (see here), so this method will work only if you are using Java 8 (or above).