Last active
March 5, 2018 21:22
-
-
Save joshlong/2abdc385f5f8b1bc26fb to your computer and use it in GitHub Desktop.
Dynamic, optional collections of beans in Spring Java `@Configuration` classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package demo; | |
import org.springframework.beans.factory.InitializingBean; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.annotation.Bean; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Optional; | |
@SpringBootApplication | |
public class DemoApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(DemoApplication.class, args); | |
} | |
/* | |
@Bean | |
Foo a() { | |
return new Foo("a"); | |
} | |
@Bean | |
Foo b() { | |
return new Foo("b"); | |
} | |
*/ | |
@Bean | |
InitializingBean bar(Optional<List<Foo>> fooList) { | |
return () -> { | |
System.out.println("fooList.size = " + fooList.map(List::size).orElse(0)); | |
System.out.println("foos.size = " + this.foos.size()); | |
System.out.println("optionalFoos.size = " + this.optionalFoos.map(List::size).orElse(0)); | |
}; | |
} | |
@Autowired(required = false) | |
private List<Foo> foos = new ArrayList<>(); | |
@Autowired | |
private Optional<List<Foo>> optionalFoos; | |
} | |
class Foo { | |
private final String name; | |
@Override | |
public String toString() { | |
return "Foo{" + | |
"name='" + name + '\'' + | |
'}'; | |
} | |
public Foo(String name) { | |
this.name = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment