在惹恼GitHub上的Spring Boot团队之前在这里发布! :)
除非我做的事情出奇的错误(很可能是这样),否则在使用Spring Boot(2.0.3)注入Optional
bean时,我会注意到 weird 模式.RELEASE)。
以下作品,我确实理解原因:
@SpringBootApplication
public class OptionalInjection {
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(OptionalInjection.class, args);
Foo foo = configurableApplicationContext.getBean(Foo.class);
System.out.println(foo.getOptionalString());
}
@Configuration
static class Config {
@Bean
public String optionalString() {
return someMethodThatReturnsAnOptional()
.orElse(null); // I so don't like unwrapping the Optional here!
}
}
@Component
static class Foo {
private final Optional<String> optionalString;
@Autowired
public Foo(Optional<String> optionalString) {
this.optionalString = optionalString;
}
public Optional<String> getOptionalString() {
return optionalString;
}
}
private static Optional<String> someMethodThatReturnsAnOptional() {
return Optional.of("Some string!");
}
}
但是我实际上想做的是:
@SpringBootApplication
public class OptionalInjection {
// ...
@Configuration
static class Config {
@Bean
public Optional<String> optionalString() {
return someMethodThatReturnsAnOptional(); // no Optional unwrapping!
}
}
// ...
}
有没有办法使第二个选项起作用?
P.S。这里必须要有构造函数注入! :)