In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
The main content of this article is "DI in-depth understanding of Spring". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "DI in-depth understanding of Spring"!
DI concept
There are actually two ways of IoC, one is DI (Dependency Injection), and the other is DL (Dependency Lookup), which is dependent lookup. The former is the dependent component that the current component passively accepts IoC container injection, while the latter is that the component actively goes to a service registry to find its dependent component. We focus on DI here.
One of the key points of IoC is to dynamically provide an object with other objects it needs while the system is running. This is achieved through DI. For example, object A needs to operate the database. In the past, we always had to write code in A to get a Connection object. With spring, we only need to tell spring,A that we need a Connection. As for how and when the Connection is constructed, A does not need to know. Through the dependency injection mechanism, we only need to specify the resources needed by the target and complete our own business logic through simple configuration without any code, without caring about where the specific resources come from and by whom. When the system is running, spring will make a Connection at the right time, and then inject it into A like an injection, thus completing the control of the relationship between the various objects. A relies on Connection to function properly, and this Connection is injected into A by spring, hence the name of dependency injection. Spring implements injection through reflection technology, which allows the program to dynamically generate objects, execute object methods, and change object properties at run time.
A brief summary of dependency injection:
Dependency: the creation of a Bean object depends on the container.
Injection: refers to the resources that the Bean object depends on, set up and assembled by the container.
The injection methods mainly include Setter injection (focus), constructor injection and parameter direct injection. There is also extension mode injection, that is, p namespace injection and c namespace injection, which will not be introduced here, and students who are interested can study it by themselves.
Setter injection
The IoC container uses the setter method to inject dependent instances. After the bean is instantiated by calling the no-parameter constructor or no-parameter static factory method, and then calling the setter method of the bean (the set method of the attribute must be in the class), the setter-based DI can be implemented.
The code is as follows:
Public class Address {
Private String address
Public String getAddress () {
Return address
}
Public void setAddress (String address) {
This.address = address
}
}
Import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class Student {private String name; private Address address; private String [] books; private List hobbys; private Map card; private Set games; private String wife; private Properties info; public void setName (String name) {this.name = name;} public String getName () {return this.name } public void setAddress (Address address) {this.address = address;} public void setBooks (String [] books) {this.books = books;} public void setHobbys (List hobbys) {this.hobbys = hobbys;} public void setCard (Map card) {this.card = card;} public void setGames (Set games) {this.games = games } public void setWife (String wife) {this.wife = wife;} public void setInfo (Properties info) {this.info = info;} public void show () {System.out.println ("name=" + name + ", address=" + address.getAddress () + ", books=") For (String book:books) {System.out.print ("\ t");} System.out.println ("\ nhobbys:" + hobbys); System.out.println ("card:" + card); System.out.println ("games:" + games); System.out.println ("wife:" + wife); System.out.println ("info:" + info);}}
Configuration file
The configuration file assigns name to Xiaoming, which completes the injection of the code private String name.
Test class
Public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("bean1.xml"); Student student= (Student) context.getBean ("student"); System.out.println (student.getName ());}
Running result, output: Xiaoming
The xml configurations of common injection methods are as follows:
Bean injection
Using ref to introduce other bean
Array injection
Mathematics, Chinese and English
List injection
Listen to music, watch movies and play games.
Map injection
Set injection
CS fights against the landlord Xiaolu.
Null injection
Properties injection
123456 male Xiaoming
Testing method
Public static void main (String [] args) {ApplicationContextcontext = new ClassPathXmlApplicationContext ("bean1.xml"); Studentstudent= (Student) context.getBean ("student"); student.show ();}
Run result, output:
Name= Xiaoming, address= Beijing, books=
Hobbys: [listening to music, watching movies, playing games]
Card: {China Merchants Bank = 123456789, ICBC = 987654321}
Games: [CS, fighting landlords, Xiaoxiele]
Wife:null
Info: {student number = 123456, gender = male, name = Xiao Ming}
Constructor injection
Means that the IoC container uses constructors to inject dependent instances. Constructor-based DI is implemented by calling constructors with parameters, each of which represents a dependency.
The code is as follows:
Public class Student2 {private String name; public Student2 (String name) {this.name = name;} public void setName (String name) {this.name = name;} public void show () {System.out.println ("name=" + name);}}
Settings in the configuration file
Test code
Public static void main (String [] args) {ApplicationContextcontext = new ClassPathXmlApplicationContext ("bean3.xml"); Student2 user = (Student2) context.getBean ("student1") user.show ();}
Running result:
Name=kevin1
Parameter direct injection
This is mainly achieved by annotations @ Autowired, @ Qualifier, and @ Resource
@ Autowired
@ Autowired is automatically transferred by type, and id matching is not supported.
Packages that need to be imported into spring-aop
Settings in the configuration file
Code:
Public class Animal {@ Autowired private Cat cat; / / Runtime spring instantiates Cat class through DI @ Autowired private Dog dog;// Runtime spring instantiates Dog class via DI public void printCatshot () {cat.shout ();} public void printDogshot () {dog.shout ();}} @ Qualifier
@ Autowired is automatically assembled according to type. If there is a different type of bean in the Spring context, a BeanCreationException exception is thrown; we can use @ Qualifier with @ Autowired to solve these problems.
Code:
@ Autowired @ Qualifier (value= "dog1") private Dog dog1; beans.xml @ Resource
@ Resource is provided by J2EE. You need to import Package: javax.annotation.Resource
@ Resource if there is a specified name attribute, first find the assembly by byName according to this attribute, and then assemble by default byName. If it is unsuccessful, an exception is reported.
Code
@ Resource (name = "dog2") private Dog dog; beans.xml 's simplest explanation
IoC mainly implements the following two points through DI technology:
When the system is running, it dynamically provides an object with other objects it needs.
In the operation of the system, the data is dynamically read from the configuration file to assign values to the properties of the object.
At this point, I believe you have a deeper understanding of "DI in-depth understanding of Spring". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 245
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.