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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…