InversionofControl (Abbreviated as IoC)
Simply put, when you need an object, you don’t need to manually new one, but other containers will provide you with it; Spring is an IOC container.
For example:
In Spring, you often need to assemble a Dao in Service, and generally use @Autowired annotation: similar to the following
public Class ServiceImpl{ @Autowired Dao dao; public void getData(){ dao.getData(); }If you use Dao directly without initialization, a null pointer exception will be reported. The method in Spring is to load the required classes for you through reflection.
Here is an example that simulates Spring's DI and IOC
First write two annotations to simulate Spring:
The Entity annotation represents the @Service@Target(ElementType.TYPE) of Spring // Class @Retention(RetentionPolicy.RUNTIME)public @interface Entity {} represents the @Autowrid@Target(ElementType.FIELD) of Spring // @Retention(RetentionPolicy.RUNTIME) of the method // Only public @interface Resources {} After the annotation is established, two classes are created:
Rain class represents the need to obtain weather data (database or server) from other places.
public class Rain { public void rain(){ System.out.println("Raining"); // I wrote it directly for convenience }}The Weather class represents the obtained weather data
@Entitypublic class Weather { @Resources Rain rain; // Here comes the rain public void weather_rain() { rain.rain(); }The following is direct injection through reflection:
First, iterate through the specified package name: this step is omitted first.
First, create a List to simulate Spring bean container, and then all the initialized classes with Entity annotations will be initialized.
public class Weather_reflect {List<Object> objectList ;// Simulate Spring container public Weather_reflect() {objectList= new ArrayList<Object>();}// In fact, the best way here is to find the class with annotations first, judge the Entity annotations and then pass them in. However, for convenience, public void get_ref(Object object) is directly omitted.Public void get_ref(Object object) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {Class<?> clazz =object.getClass();if(clazz.isAnnotationPresent(Entity.class)){//Judge whether it has Entity annotation Field[] fields =clazz.getDeclaredFields();//Get its variable for (Field field :fields){if(field.isAnnotationPresent(Resources.class)){//Judge whether Class<?> rainClass=Class.forName(field.getType().getName(), false,Thread.currentThread().getContextClassLoader());// Here first load the Rain class field.set(object,rainClass.newInstance());// Assign to rainobjectList.add(object);// Finally save the assigned Weather into the container}}}}} public List<Object> returnList(){return objectList;//Return the container for future use}Finally, it is to simulate the use of the Controller directly
public class WeatherPrediction {public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {WeatherPrediction weatherPrediction =new WeatherPrediction();Weather weather =(Weather)weatherPrediction.springDo();weather.weather_rain();// If it is a normal call, a null pointer exception will be reported, and the container assigns the rain variable to it, so it can output normally}/* Simulate the Spring startup process. In fact, you can write a class separately. This step is what the container should do, and we don't need to worry about it*/public Object springDo() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Weather_reflect weather_reflect =new Weather_reflect();// Weather weather =new when it starts Weather();//Scan the class annotation and then proceed to the next step weather_reflect.get_ref(weather);// New operation of the variables in its class and put them into the container Object object =weather_reflect.returnList().get(0);return object;}Open the output: It is rainingThere is no new operation on Rain in WeatherPrediction, but it can be used. This should be the simplest IOC example to simulate Spring. Of course, Spring's IOC container is much more powerful than this, such as thread safety needs to be considered, and various details are required.
Summarize
The above is all the detailed explanation of this article on the simple implementation of Spring's IOC principle, I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Detailed explanation of Spring IOC principles
A brief understanding of Spring's IOC, AOP and code examples
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!