Home Java javaTutorial Detailed explanation of several methods of dependency injection in Java Spring

Detailed explanation of several methods of dependency injection in Java Spring

Mar 06, 2017 am 10:06 AM

This article mainly introduces several methods of Spring dependency injection in detail. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Introduction to IoC

In ordinary Java development, programmers need to rely on methods of other classes in a certain class.

Usually new is a method of relying on a class and then calling a class instance. The problem with this kind of development is that new class instances are not easy to manage uniformly.

Spring puts forward the idea of ​​dependency injection, that is, dependent classes are not instantiated by programmers, but the Spring container helps us specify new instances and inject the instances into classes that require the object.

Another term for dependency injection is "inversion of control". The popular understanding is: usually we create a new instance, and the control of this instance is our programmer.

Inversion of control means that the new instance work is not done by our programmers but is handed over to the Spring container.

Spring has multiple forms of dependency injection. This article only introduces how Spring performs IOC configuration through xml.

1.Set injection

This is the simplest injection method. Suppose there is a SpringAction and a SpringDao object needs to be instantiated in the class, then you can define a private SpringDao member variables, and then create the set method of SpringDao (this is the injection entry of ioc):

Then write the spring xml file, the name attribute in is an alias of the class attribute, and the class attribute Refers to the full name of the class. Because there is a public property Springdao in SpringAction, a tag must be created in the tag to specify SpringDao. The name in the tag is the SpringDao property name in the SpringAction class, and the ref refers to the following . In this way, spring actually instantiates the SpringDaoImpl object and calls the setSpringDao method of SpringAction to SpringDao injection:

<!--配置bean,配置后该类由spring管理--> 
<bean name="springAction" class="com.bless.springdemo.action.SpringAction"> 
<!--(1)依赖注入,配置当前类中相应的属性--> 
<property name="springDao" ref="springDao"></property> 
</bean> 
<bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>
Copy after login

2. Constructor injection

This method of injection refers to injection with parameters Constructor injection, look at the example below. I created two member variables SpringDao and User, but did not set the set method of the object, so the first injection method cannot be supported. The injection method here is in the constructor of SpringAction. Injection, that is to say, when creating a SpringAction object, the two parameter values ​​​​of SpringDao and User must be passed in:

public class SpringAction { 
//注入对象springDao 
private SpringDao springDao; 
private User user; 

public SpringAction(SpringDao springDao,User user){ 
this.springDao = springDao; 
this.user = user; 
System.out.println("构造方法调用springDao和user"); 
} 

public void save(){ 
user.setName("卡卡"); 
springDao.save(user); 
} 
}
Copy after login

also does not use tag, and the ref attribute also points to the name attribute of other tags:

<!--配置bean,配置后该类由spring管理--> 
<bean name="springAction" class="com.bless.springdemo.action.SpringAction"> 
<!--(2)创建构造器注入,如果主类有带参的构造方法则需添加此配置--> 
<constructor-arg ref="springDao"></constructor-arg> 
<constructor-arg ref="user"></constructor-arg> 
</bean> 
<bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean> 
<bean name="user" class="com.bless.springdemo.vo.User"></bean>
Copy after login

Resolve the construction Uncertainty of method parameters. You may encounter that the two parameters passed in by the constructor are of the same type. In order to distinguish which one should be assigned the corresponding value, you need to do some small processing:

The following It is to set the index, which is the parameter position:

<bean name="springAction" class="com.bless.springdemo.action.SpringAction"> 
<constructor-arg index="0" ref="springDao"></constructor-arg> 
<constructor-arg index="1" ref="user"></constructor-arg> 
</bean>
Copy after login

The other is to set the parameter type:

<constructor-arg type="java.lang.String" ref=""/>
Copy after login

3. Static factory method injection

As the name suggests, the static factory is to obtain the objects you need by calling the static factory method. In order for spring to manage all objects, we cannot Obtain the object directly through "Engineering Class. Static Method ()", but still obtain it through spring injection:

package com.bless.springdemo.factory; 

import com.bless.springdemo.dao.FactoryDao; 
import com.bless.springdemo.dao.impl.FactoryDaoImpl; 
import com.bless.springdemo.dao.impl.StaticFacotryDaoImpl; 

public class DaoFactory { 
//静态工厂 
public static final FactoryDao getStaticFactoryDaoImpl(){ 
return new StaticFacotryDaoImpl(); 
} 
}
Copy after login

Also look at the key class, here I need to inject a FactoryDao object. It looks exactly the same as the first injection, but if you look at the subsequent xml, you will find a big difference:

public class SpringAction { 
//注入对象 
private FactoryDao staticFactoryDao; 

public void staticFactoryOk(){ 
staticFactoryDao.saveFactory(); 
} 
//注入对象的set方法 
public void setStaticFactoryDao(FactoryDao staticFactoryDao) { 
this.staticFactoryDao = staticFactoryDao; 
} 
}
Copy after login

Spring IOC configuration file, please note that the class pointed by is not the implementation class of FactoryDao, but points to the static factory DaoFactory, and configure factory-method="getStaticFactoryDaoImpl" to specify which factory method to call:

<!--配置bean,配置后该类由spring管理--> 
<bean name="springAction" class="com.bless.springdemo.action.SpringAction" > 
<!--(3)使用静态工厂的方法注入对象,对应下面的配置文件(3)--> 
<property name="staticFactoryDao" ref="staticFactoryDao"></property> 
</property> 
</bean> 
<!--(3)此处获取对象的方式是从工厂类中获取静态方法--> 
<bean name="staticFactoryDao" class="com.bless.springdemo.factory.DaoFactory" factory-method="getStaticFactoryDaoImpl"></bean>
Copy after login

4. Instance factory method injection

The instance factory means that the method of obtaining the object instance is not static. So you need to first create a new factory class, and then call the ordinary instance method:

public class DaoFactory { 
//实例工厂 
public FactoryDao getFactoryDaoImpl(){ 
return new FactoryDaoImpl(); 
} 
}
Copy after login

The following class has nothing to say, it is very similar to the previous one, but we You need to create a FactoryDao object through the instance factory class:

public class SpringAction { 
//注入对象 
private FactoryDao factoryDao; 

public void factoryOk(){ 
factoryDao.saveFactory(); 
} 

public void setFactoryDao(FactoryDao factoryDao) { 
this.factoryDao = factoryDao; 
} 
}
Copy after login

Finally look at the spring configuration file:

<!--配置bean,配置后该类由spring管理--> 
<bean name="springAction" class="com.bless.springdemo.action.SpringAction"> 
<!--(4)使用实例工厂的方法注入对象,对应下面的配置文件(4)--> 
<property name="factoryDao" ref="factoryDao"></property> 
</bean> 

<!--(4)此处获取对象的方式是从工厂类中获取实例方法--> 
<bean name="daoFactory" class="com.bless.springdemo.factory.DaoFactory"></bean> 
<bean name="factoryDao" factory-bean="daoFactory" factory-method="getFactoryDaoImpl"></bean>
Copy after login

5. Summary

The most commonly used Spring IOC injection methods are (1) (2). The more you write and practice, the more you will become very proficient.

Also note: Objects created through Spring are singletons by default. If you need to create multiple instance objects, you can add an attribute after the tag:

<bean name="..." class="..." scope="prototype">
Copy after login

The above is a detailed explanation of several methods of Java Spring dependency injection. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Explain the concept of Dependency Injection (DI) in PHP. Explain the concept of Dependency Injection (DI) in PHP. Apr 05, 2025 am 12:07 AM

The core value of using dependency injection (DI) in PHP lies in the implementation of a loosely coupled system architecture. DI reduces direct dependencies between classes by providing dependencies externally, improving code testability and flexibility. When using DI, you can inject dependencies through constructors, set-point methods, or interfaces, and manage object lifecycles and dependencies in combination with IoC containers.

See all articles