Spring injection with Java's Optional

Viewed 2640

When trying to inject an Optional<T>, Spring never calls my bean, and instead injects an Optional.empty().

Here is some sample code:

@Configuration
public class Initialize {

    @Value("optionalValue")
    private String testString;

    @Bean (name = "getOptionalString")
    public Optional<String> getOptionalString() {
        return Optional.of(this.testString); //breakpoint put here, is never called
    }
}

@Component
public class Test {

    public Test(@Qualifier("getOptionalString") Optional<String> optional) {
      // optional's value is Optional.empty() here
    }

I noticed that (by putting a breakpoint) the @Bean is never called. If I were to remove the Optional<String>, and simply return a String, then it works!

I know Spring has its own optional dependency but I am perplexed as to why this doesn't work (whatever I read online says it should), and I also don't understand how it initialized it to Optional.empty()?

1 Answers

The documentation says:

you can express the non-required nature of a particular dependency through Java 8’s java.util.Optional, as the following example shows:

public class SimpleMovieLister {

    @Autowired
    public void setMovieFinder(Optional<MovieFinder> movieFinder) {
        ...
    }
}

So using Optional as the type of a bean is not a good idea.

Related