Java Spring boot uses spring reflection and bootspring
Spring reflection
1. You can instantiate this class by class name.
ApplicationContext. getBean (name)
2. Get classes by type
applicationContext.getBeansOfType(clazz);
First, you must obtain the spring container. The ApplicationContextAware interface in the class can obtain applicationContext.
You can write the bean retrieval method to a tool class to implement ApplicationContextAware, and define applicationContext as a constant for convenient calling.
1 private static ApplicationContext applicationContext = null; 2 3 @Override 4 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 5 if (SpringUtil.applicationContext == null) { 6 SpringUtil.applicationContext = applicationContext; 7 } 8 } 9 10 public static ApplicationContext getApplicationContext() {11 return applicationContext;12 }13 14 public static <T> Map<String, T> getBeanOfType(Class<T> clazz) {15 return getApplicationContext().getBeansOfType(clazz);16 }17 18 public static Object getBean(String name) {19 return getApplicationContext().getBean(name);20 }21 22 public static <T> T getBean(Class<T> clazz) {23 return getApplicationContext().getBean(clazz);24 }25 26 public static <T> T getBean(String name, Class<T> clazz) {27 return getApplicationContext().getBean(name, clazz);28 }
The xml <bean> configuration is omitted in the spring boot framework, and the @ Bean is injected into the configuration class, so that spring can find the tool class written in.
In the implementation of polymorphism, sometimes many judgments are required to execute different implementations. In this case, you can find the interface to be executed by implementing the class name or interface.
For example
1 Map<String, IAddReceipt> map = SpringUtil.getBeanOfType(IAddReceipt.class);2 for (IAddReceipt addReceipt : map.values()) {3 addReceipt.save(addReceiptVO);4 }
I want to implement a function. He divided several modules into the save action. I defined an iaddreceipin interface, which is a save method, I have created an IAddReceipt implementation class for the save of these modules. Each implementation class has its own operations, so that I can get the implementation class of this interface and put it in map, then, traverse the map and call the save method.
In this way, the operations on each module are completed in the main method.