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.
@Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors. Injectable fields: are annotated with @Inject .
Before Spring 4.3, we had to add an @Autowired annotation to the constructor. With newer versions, this is optional if the class has only one constructor.
JSR 330 @Named annotation is equivalent to spring @Component and @Inject is equivalent to spring @Autowired in spring container with some limitations. A bean annotated with @Named annotation is considered as a component in spring container.
@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application. Sr.
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).
No... there is no equivalent for optional in JSR 330... if you want to use optional injection then you will have to stick with the framework specific @Autowired
annotation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With