通过Spring将继承树加载到List中
我注意到有趣的Spring功能。 我的一位同事使用它将Spring Bean的整个继承树加载到列表中。 在学习Spring文档时错过了这一点。
让我们来看看Spring bean的继承树:
下面的代码片段是通过构造函数注入将该豆树加载到列表中的:
@Component public class Nature { List<Animal> animals; @Autowired public Nature(List<Animal> animals) { this.animals = animals; } public void showAnimals() { animals.forEach(animal -> System.out.println(animal)); } }
方法showAnimals使用Java 8 lambda表达式将已加载的bean输出到控制台中。 这些天来,您会发现很多有关此新Java 8功能的文章。
Spring上下文由这个主类加载:
public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringContext.class); Nature nature = context.getBean(Nature.class); nature.showAnimals(); } }
控制台输出:
PolarBear [] Wolf [] Animal [] Grizzly [] Bear []
- 有时此功能可能很方便。 这个简短示例的源代码在Github上 。
翻译自: https://www.javacodegeeks.com/2014/05/load-inheritance-tree-into-list-by-spring.html