What are the three methods of Spring dependency injection?
The three methods of Spring dependency injection (DI) are:
1, interface injection
2, Setter method injection
3. Constructor method injection
(Video tutorial recommendation: java video)
Let me introduce to you how these three types of dependency injection work in Spring. realized.
First we need the following classes:
Interface Login.java
Interface implementation class LoginImpl.java
A processing class LoginAction.java
There is also a test class TestMain.java
LoginImpl.java as follows:
package com.spring.test.di; public class LoginImpl implements Login{ public String getName(){ return "fengyun"; } } TestMain.java package com.spring.test.di; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class TestMain { /** * @param args */ public static void main(String[] args) {// 得到ApplicationContext对象 ApplicationContext ctx = new FileSystemXmlApplicationContext( "applicationContext.xml"); // 得到Bean LoginAction loginAction = (LoginAction) ctx.getBean("loginAction"); loginAction.execute(); } }
LoginAction.java will be slightly different depending on the injection method used.
Let’s look at the LoginAction.java class according to the injection method
Setter method injection:
package com.spring.test.di; public class LoginAction { private Login login; public void execute() { String name = login.getName(); System.out.print("My Name Is " + name); } /** * @return the login */ public Logic getLogin() { return login; } /** * @param login * the login to set */ public void setLogin(Login login) { this.login = login; } }
defines a Login type variable login, in LoginAction does not instantiate login, but only its corresponding setter/getter method, because we are using Spring's dependency injection method here.
The applicationContext.xml configuration file is as follows:
<bean id="login" class="com.spring.test.di.LoginImpl"/> <bean id="loginAction" class="com.spring.test.di.LoginAction"> <property name="login" ref="login"></property> </bean>
Now you can run testMain.java, and we can see that My Name Is fengyun is printed on the console.
OK, this is spring’s setter method injection.
Constructor method injection
As the name suggests, constructor method injection means that we rely on the constructor method of LoginAction to achieve the purpose of DI, as shown below:
LoginAction.java package com.spring.test.di; public class LoginAction { private Login login; public LoginAction(Login login) { this.login = login; } public void execute() { String name = login.getName(); System.out.print("My Name Is " + name); } }
Here we have added a LoginAction constructor
applicationContext.xml configuration file is as follows:
<bean id="login" class="com.spring.test.di.LoginImpl"/> <bean id="loginAction" class="com.spring.test.di.LoginAction"> <constructorarg index="0" ref="login"></constructorarg> </bean>
We use constructorarg for configuration. The index attribute is used to indicate the order of parameters in the constructor. , if there are multiple parameters, configure them in order from 0,1...
We can now run testMain.java, and the result is exactly the same as using the Setter method to inject.
One thing to note is: if the constructor has multiple parameters, such as: parameter 1, parameter 2, and parameter 2 depends on parameter 1, in this case, you must pay attention to the order of the constructor, and the parameters must be 1 is placed before parameter 2.
Let’s continue talking about interface injection that we don’t commonly use. Let’s take LoginAction as an example. We have modified it as follows:
LoginAction.java package com.spring.test.di; public class LoginAction { private Logic login; public void execute() { try { Object obj = Class.forName("com.spring.test.di.LoginImpl") .newInstance(); login = (Login) obj; String name = login.getName(); System.out.print("My Name Is " + name); } catch (Exception e) { e.printStackTrace(); } } }
Configuration file:
<bean id="logic" class="com.spring.test.di.LoginImpl"/> <bean id="loginAction" class="com.spring.test.di.LoginAction"> </bean>
The two most commonly used injection methods at work are Setter and constructor.
Recommended tutorial: java entry program
The above is the detailed content of What are the three methods of Spring dependency injection?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

JUnit is a widely used Java unit testing framework in Spring projects and can be applied by following steps: Add JUnit dependency: org.junit.jupiterjunit-jupiter5.8.1test Write test cases: Use @ExtendWith(SpringExtension.class) to enable extension, use @Autowired inject beans, use @BeforeEach and @AfterEach to prepare and clean, and mark test methods with @Test.

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto

In Go, the dependency injection (DI) mode is implemented through function parameter passing, including value passing and pointer passing. In the DI pattern, dependencies are usually passed as pointers to improve decoupling, reduce lock contention, and support testability. By using pointers, the function is decoupled from the concrete implementation because it only depends on the interface type. Pointer passing also reduces the overhead of passing large objects, thereby reducing lock contention. Additionally, DI pattern makes it easy to write unit tests for functions using DI pattern since dependencies can be easily mocked.

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.
