If you want to call a method in a spring bean, and the method’s name is unknown, you should
use java reflection to call the method.
1. Pom.xml
Here we use spring boot 1.4.3
2. Define two spring beans
Here we define two beans:
- The first bean is the server bean, which would call the second bean’s method by reflection
- The second bean is the bean to be called by the server bean, supply some methods to be called
3. Use java reflection to call the MethodsBean’s any method
Now it’s the trick:
The core steps are as follows:
- use appContext to get the bean object
- use methodName as the param to search for the Method object
- if got the method object, then use java reflection to invoke the method
You can find detail documents about the springboot and java reflection here: