Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...