Three injection methods of spring (1) Constructor injection

Spring's dependency injection is divided into three ways

1. Constructor injection

2.setter injection

3. Interface injection

Constructor injection and setter injection are the two main ways of dependency injection, and interface injection refers to the way of injection from other places.

 

What I'm going to introduce next is Constructor Injection

Constructor injection depends on the implementation of the constructor, which can be parameterized or parameterless.

In most cases, we create class objects through constructors,

Spring can use reflection to complete the injection through the construction method, which is the principle of the construction method.

1. Introduce spring support

2. By describing specific classes, construction methods and parameters, spring can create objects by reflection through corresponding information.

3. The method of loading the spring configuration file in the test file

String configLocation ="applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);

Role role = context.getBean("role", Role.class);

All resources in spring are beans.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325295580&siteId=291194637