In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to understand IoC dependency injection". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand IoC dependency injection".
Annotation-driven IoC
The xml-driven IoC container uses ClassPathXmlApplicationContext to read bean information in xml.
The annotation-driven IoC container uses AnnotationConfigApplicationContext to read bean information in the Java class
1. Registered use of AnnotationConfigApplicationContext
Compared with the xml file as the driver, the annotation driver needs to specify the configuration class. A configuration class can be understood as "equivalent" to a xml configuration class. You only need to mark @ Configuration on the class.
@ Configuration public class DemoConfiguration {}
How to declare bean in xml
The @ Bean annotation is used in the configuration class
Note: register a Bean with the type Persion,id Person with the IoC container
The method name indicates that the id return value of bean indicates the type of registered bean.
@ Bean annotations can also be displayed declaring that bean's id such as @ Bean ("person1")
@ Bean public Person person () {return new Person ();}
two。 Initialization of annotated IoC container
Public class AnnotationConfigApplication {public static void main (String [] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext (DemoConfiguration.class); Person person = ctx.getBean (Person.class); System.out.println (person);}}
After running, the Person console prints the result
Com.huodd.bean.Person@55536d9e
3. Registration and scanning of components
In the initialization above, we passed the parameter Class... when using AnnotationConfigApplicationContext. ComponentClasses
If you look at the construction method of AnnotationConfigApplicationContext, you can find that the parameter types that can also pass parameters are String.... BasePackages
This involves the registration and scanning of components.
Here is a question to consider: if we have a lot of components to register, there will be a lot of code work to write these @ Bean. How to solve this problem?
Spring provides us with several annotations that can help us quickly register the components we need, which are called pattern annotations (stereotype annotations).
@ Component
@ Component can be said to be the root of all component registrations. Marking @ Component on the class means that the class is registered in the IoC container as a Bean.
@ Component public class Person {}
If the name of Bean is not specified, the default rule is "Class name with lowercase". The bean name above will be person by default.
If you want to customize the name of bean, you can declare the value of value in @ Component, such as
@ Component ("person1") public class Person {}
In xml is equivalent to
@ ComponentScan
At this time, if we run the startup class directly to get the bean object of Person, we will get the wrong NoSuchBeanDefinitionException. Why?
Because we just declare the component, and then start the IoC container directly, so that the container is not aware of the existence of @ Component
Solution 1:
We need to write a new annotation @ ComponentScan when we write the configuration class
The goal is to tell the IoC container which package I want to scan under the class with the @ Component annotation
@ Configuration @ ComponentScan ("com.huodd.bean") public class DemoComponentScanConfiguration {}
Note: if you do not specify a scanning path, the components with @ Component under the package in this class and all subpackages will be scanned by default
The startup class code is as follows:
Public class AnnotationConfigApplication {public static void main (String [] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext (DemoComponentScanConfiguration.class); Person person = ctx.getBean (Person.class); System.out.println (person);}}
Solution 2:
Instead of writing @ ComponentScan, you can directly pass the String type packet scan path code in the AnnotationConfigApplicationContext method parameters as follows
Public class AnnotationConfigApplication {public static void main (String [] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext ("com.huodd.bean"); Person person = ctx.getBean (Person.class); System.out.println (person);}}
PS: component scanning is not unique to annotation-driven IoC. In fact, component scanning can also be enabled in xml-driven IoC mode. You only need to declare a tag in xml.
It should be noted here: if you need to scan multiple paths, you need to write multiple tags, that is, a tag can only declare one root package.
Supplement to component registration
SpringFramework provides extended notes when developing a three-tier architecture for Web: are you familiar with @ Controller, @ Service, and @ Repository, respectively?
These three annotations represent the presentation layer, the business layer and the persistence layer, respectively. The function of these three annotations is exactly the same as @ Component. We can see that the bottom layer adds @ Component to these three annotation classes.
@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented @ Component public @ interface Service {}
In this way, we can directly mark @ Service and other annotations for the corresponding ones such as ServiceImpl when we carry out the development that conforms to the three-tier architecture.
@ Configuration
@ Configuration also has the tag @ Component at the bottom.
@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented @ Component public @ interface Configuration {...}
This shows that the configuration class is not just a configuration as we think, it will also be regarded as bean and registered in the IoC container.
4. Annotation driver and xml driver refer to each other
4.1 xml citation comments
You need to open the annotation configuration and register the corresponding configuration class.
4.2 comments citing XMl
@ Configuration @ ImportResource ("classpath:annotation/demo-beans.xml") public class ImportXmlAnnotationConfiguration {}
2. Dependency injection of IoC
1.Setter attribute injection
Create an object and return the object after entering the attribute value set
@ Bean public Person person () {Person person = new Person (); person.setId (1); person.setName ("PoXing"); person.setAge (18); return person;}
Setter injection in xml
two。 Constructor injection
To use constructor injection, you need to add parametric constructors to bean itself, such as adding parameterized constructors to Person as follows
Public Person (Integer id, String name, Integer age) {this.id = id; this.name = name; this.age = age;}
In the annotation driver, we need to specify parameter values when we inject attributes when we create a bean.
@ Bean public Person person () {return new Person (1, "PoXing", 18);}
The xml driver is as follows
3. Annotated attribute injection
Let's first explain why there is annotated attribute value injection. Careful friends may find that the Setter attribute injection and constructor injection mentioned above can only be used when using the @ Bean annotation, but if you mark the component of the @ Component annotation (like the @ Component annotation in our Person class above), how to set the property value? this section is mainly about this section.
Attribute injection under @ Component
Here we use the Dog class as a demonstration (here I quietly added @ Component to note that the friends I tried should be careful, or they will report an error.)
@ Component public class Dog {private Integer id; private String name; private Integer age;... Omit Getter, Setter... Omit toString}
To implement annotated attribute injection, you can directly mark @ Value annotation on the field to be injected, as shown in
@ Value ("1") private Integer id; @ Value ("wangcai") private String name; @ Value ("3") private Integer age
The startup class code is as follows
Public class DiApplication {public static void main (String [] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext ("com.huodd.bean"); Dog dog = ctx.getBean (Dog.class); System.out.println (dog);}}
Console print results
Dog {id=1, name='wangcai', age=3}
External configuration file (@ PropertySource)
The main problem here is to solve the above @ Value injection. We have fixed the attribute value directly. If we want to modify it, we have to modify it in the Java code, which is not in line with the development specification.
SpringFramework extends the new annotation @ PropertySource for us mainly to import external configuration files
1. Here we create a dog.properties
Dog.id=1 dog.name=wangcai dog.age=3
two。 Bring in a profile
@ PropertySource ("classpath:di/dog.properties") @ ComponentScan ("com.huodd.bean") @ Configuration public class DemoComponentScanConfiguration {}
Attribute injection in the 3.Dog class where @ Value needs to cooperate with placeholders to get the contents of the properties configuration file
@ Value ("${dog.id}") private Integer id; @ Value ("${dog.name}") private String name; @ Value ("${dog.age}") private Integer age
4. Modify the startup class
Public class DiApplication {public static void main (String [] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext (DemoComponentScanConfiguration.class); Dog dog = ctx.getBean (Dog.class); System.out.println (dog);}}
The console print results are as follows
Dog {id=1, name='wangcai', age=3}
At this point, the properties of the configuration file have been injected successfully
4. Automatic injection
There is a ref attribute in xml mode to inject one bean into another bean, as well as in annotation mode
@ Autowired
Inject Person's Bean into Dog's bean (that is, assign dog its owner)
Method 1 → tagging on attributes
@ Component public class Dog {/ / @ Autowired private Person person;}
Method 2 → uses constructor injection
@ Component public class Dog {/ / Private Person person; @ Autowired public Dog (Person person) {this.person = person;}}
Method 3 → is injected using the setter method
@ Component public class Dog {/ / Private Person person; @ Autowired public void setPerson (Person person) {this.person = person;}}
@ Resource under the JSR250 specification
@ Resource is also an annotation for attribute injection
The difference between it and @ Autowired is:
@ Autowired is injected by type
@ Resource is injected according to the name of the attribute (that is, the name of bean)
The @ Resource annotation is equivalent to the annotations @ Autowired and @ Qualifier
@ Qualifier is briefly described here. It exists to specify the name of bean. If there are multiple identical bean but different names of bean, we can use @ Autowired to configure @ Qualifier annotation.
For example, the following indicates that the host Bean injected by the Dog class is named xiaowang, while there may be multiple host bean objects such as xiaoli and xiaoming in the current container.
@ Component public class Dog {/ / @ Autowired @ Qualifier ("xiaowang") private Person person;}
If you use @ Resource below, the code is more convenient as follows
@ Component public class Dog {/ / @ Resource (name= "xiaowang") private Person person;}
@ Inject under the JSR330 specification
@ Inject annotations are also injected by type, the same as the strategy of @ Autowire, but additional import dependencies are required to use @ Inject
Javax.inject javax.inject 1
The latter method is the same as the native @ Autowire + @ Qualifier of SpringFramework.
@ Component public class Dog {@ Inject / / equivalent to @ Autowired @ Named ("xiaowang") / / equivalent to @ Qualifier private Person person
The difference between it and @ Autowired is:
The package in which @ Autowired resides is org.springframework.beans.factory.annotation.Autowired, which is provided by SpringFramework.
The package @ Inject is javax.inject.Inject belongs to the specification of JSR, which means that you can use this annotation if you are not using SpringFramework
5. Complex type injection
Array injection
PoXing LaoWang
List injection
13000000000 13000000001
Set injection-
-
Map injection
Properties injection
Male 18
Interview questions
What is the principle of 1.@Autowired injection?
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
First take the type corresponding to the attribute and go to the IoC container to find the corresponding Bean
If it is not found, throw a NoUniqueBeanDefinitionException exception directly
If you find a direct return
If you find multiple bean of the same type, then compare the attribute name with the id of these multiple bean
If there are multiple or none, a NoUniqueBeanDefinitionException exception will be thrown
If only one returns directly
two。 What are the ways of dependency injection and what is the difference?
3. Annotation comparison of automatic injection
Qualifier: if the annotated member / method finds more than one Bean of the same type when injecting based on the type, it will look for a specific bean based on the name declared by the annotation
@ Primary: if multiple Bean of the same type are registered in the IOC container at the same time, the default policy is the bean that injects the @ Primary annotation when using the annotation of "injecting according to type"
4. What are the advantages and disadvantages of using dependency injection
As one of the implementation methods of IOC, the purpose of dependency injection is to decouple. We do not need to new those dependent class objects directly from the container to use them. If components have multi-level dependencies, dependency injection can simplify these dependencies.
Configurability of dependent objects: through xml or annotation declaration, the objects injected by components can be specified and adjusted. With the polymorphic feature of Java, the object replacement of dependency injection can be completed without mass modification.
Thank you for reading, the above is the content of "how to understand the dependency injection of IoC". After the study of this article, I believe you have a deeper understanding of how to understand the dependency injection of IoC, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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: 0
*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.