Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 823
Eric B. Avatar asked Oct 21 '13 03:10

Eric B.


People also ask

Is @inject required?

@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 .

Is @autowired optional?

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.

Which is the Spring equivalent to the @inject JSR 330 annotation?

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.

What is the difference between @inject and @autowired?

@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.


2 Answers

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

like image 182
Utku Özdemir Avatar answered Sep 24 '22 00:09

Utku Özdemir


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

like image 38
Arun P Johny Avatar answered Sep 21 '22 00:09

Arun P Johny