Avant de lire cet article, vous pouvez d'abord vous référer à l'article " Comprendre l'injection de dépendance et le contrôle de l'inversion au printemps " pour en savoir plus sur le contenu pertinent de l'injection de dépendance et de l'inversion de contrôle.
Trois façons d'injection de dépendance
Injection de propriété, injectez la valeur de la propriété du bean via la méthode du secteur ou l'injection de méthode d'usine d'injection d'objet dépendant (rarement utilisé)
exemple
Ici, nous utilisons Spring-4.3.2, fichier de configuration maven
<dependency> <proupId> org.springframework </proncId> printemps-core </ artifactId> <DERSE> $ {org.springFramework-Version} </ version> <exclusions> </clusion> <proupId> Commons-Logging </rom grouped> Commons-Logging </RetifActid> </clusion> <GroupId> org.springFramework </rom groupeid> Spring-Beans </ ArtifactId> <Dersion> $ {org.springFramework-Version} </ Version> </Dependance> <Dependance> <ProupId> org.springFramework </romp grouped> printemps-AOP </ artifactid> <version> $ {org.springframework-version} </ version> </dependency> <dependency> <proupId> org.springframework </pr grouped> printemps-context </ artifactid> <version> $ {org.spridframework-version </preinty> </dedency> <pedency> <proupId> Commons-Logging </prewrid> Commons-Logging </ ArfactId> <Dersion> 1.2 </DERNIFRIMENTS> </ Dependency> <! - JUnit -> <Dependance> <GroupId> JUnit </ProupId> JUnit </ ArtiFactId> <DersonD> 3.8.1 </preinte> <ccope> Test </ Scope> </Dependance>Fichier de configuration d'applicationContext.xml
<! -? xml version = "1.0" Encoding = "utf-8"? -> <Beans xmlns = "https://www.springframework.org/schema/beans" xmlns: p = "https://www.springframework.org/schema/p" xmlns: util = "https://www.springframework.org/schema/util" xmlns: xsi = "https://www.w3.org/2001/xmlschema-instance" xsi: schemalation = "https://www.springframeworkwork https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd "> <! Classe: Le nom complet de la classe du bean dans le conteneur et créez un bean dans le conteneur IOC par réflexion, de sorte que la classe Bean doit avoir un constructeur de paramètres -> <bean id = "Helloworld"> <propriété name = "name" value = "cristal"> </ propriété> </EAN> <! - Configuration des beans via des méthodes de constructeur -> <pEled vous permet de spécifier "le type de paramètres pour distinguer les constructeurs. <constructor-arg index = "0" value = "benchi"> </ constructor-arg> <constructor-arg index = "1" type = "double" value = "200000.0"> </ constructor-arg> </Ean> <bean id = "car1"> <! - Si le littéral contient des caractères spéciaux, use <! [cdata [] ]> type = "java.lang.string"> <value> <! - [cdata [<shanghai ->]]> </value> </ constructor-arg> <constructor-arg index = "1" type = "int" value = "200"> </ constructor-arg> </ bean> <bean id = "personne"> <propriété name = "name" value = "cristal"> </ property = "property =" Age " value="20"></property> <!-- You can use ref to create relationships between references--> <!-- <property name="car" ref="car"></property> --> <!-- <property name="car"> <ref bean="car2"/> </property> --> <!-- <property name="car"> <bean> <constructor-arg value="changanFute"></constructor-arg> <constructor-arg Value = "3000000"> </ Constructor-Arg> <Constructor-Arg Value = "240"> </ Constructor-Arg> </anEn> </ Property> -> <! - Test Assignment Null -> <! - <propriété name = "Car"> <Null /> </ Property> -> <Propriété Name = "Car" Ref = "Car1"> </ Property> <! - Assignez les valeurs de Cascading Promescading. Remarque: les propriétés doivent être initialisées avant de pouvoir se voir attribuer des valeurs aux propriétés en cascade. Ils sont différents de Structs2 -> <propriété name = "car.price" value = "400000"> </ propriété> </ bean> <! - Test Configuration Collection Properties -> <bean id = "Person3"> <propriété name = "name" value = "Property"> </ propriété> <propriété name = "Age" Value = "21"> </ Property </ Property Name = "Cars"> <Sist> bean = "car1"> <an bean> <constructor-arg value = "changanfute"> </ constructor-arg> <constructor-arg value = "3000000"> </ constructor-arg> <constructor-arg value = "240"> </ constructor-arg> </ank> </ Ref> </ref> </ list> </premy> </pEan> <! id = "newPerson"> <propriété name = "name" value = "lina"> </ propriété> <propriété name = "age" value = "22"> </ propriété> <propriété name = "CARS"> <! - Utilisez le nœud de carte et la cartographie du nœud enfant pour configurer les variables membre de la carte -> <map> <entrée clé = "aa" value-ref x Value-ref = "car1"> </ entrée> </ map> </ propriété> </ bean> <! - Configurer les propriétés Valeur de propriétés -> <bean id = "DataSource"> <propriété name = "Properties"> <! - Utilisez des accessoires et des enfants pour attribuer des valeurs aux propriétés Properties -> <props> <prop. key = "jdbcurl"> jdbc: mysql: // test </ prop> <prop key = "jdbcdriver"> com.mysql.jdbc.driver </prop> </ props> </ propriété> </ bean> <! - Configurez un bean de collection singleton pour référence par plusieurs beans. Vous devez importer l'espace de noms Util -> <util: list id = "cars"> <ref bean = "car"> <ref bean = "car1"> </ ref> </ ref> </ util: list> <bean id = "person4"> <propriété name = "name" value = "jackie"> </ property </bant> <! - Attribution de valeurs aux propriétés du bean via l'espace de noms P, vous devez d'abord importer l'espace de noms p, ce qui est plus concis que les méthodes de configuration traditionnelles -> <bean id = "Person5" P: Age = "32" P: Cars-Ref = "CARS" P: Name = "Queue"> </ank> </EANS>
1. Vous trouverez ci-dessous des classes de test d'injection d'attributs simples
Voiture
Package com.spring.test; Classe publique Car {Nom de chaîne privée; private int maxspeed; Double Private; Public Car () {} Public Car (nom de chaîne, Double Price) {this.name = name; this.price = Price;} public Car (String Name, int maxspeed) {this.name = name, le prix de la mèche = maxspeed;} {this.name = name; this.price = prix; this.maxspeed = maxSpeed;} public void setPrice (double prix) {this.price = prix;} @ override public String toString () {return "car [name:" + name + ", prix:" + prix + ", maxSpeed:" + maxspeed + "]";}}Helloworld.java
Package com.spring.test; classe publique Helloworld {nom de chaîne privée; public helloworld () {System.out.println ("Helloworld Constructor ...");} public String getName () {return name;} public void setName (String name) {System.out.print @ @ overnide Trow {return "Hello," + name;}}Personne.java
Package com.spring.test; Public Class Person {Nom de chaîne privée; Int privé; voiture public Car; public String getName () {Nom de retour;} public void setName (nom de la chaîne) {this.name = name;} public int grenage () {return age;} public void Setage (int Age) {this.age = age;} work Car Getcar () {Retour Car {this.car = car;} @ override public String toString () {return "personne: [name =" + name + ", age =" + age + ", car =" + car + "]";}}Main.java
package com.spring.test; import org.junit.test; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; public class main {public static void main Helloworld (); hello.setName ("Barry"); System.out.println ("print:" + hello + "/ n"); // Chargez le fichier de configuration de Spring / ** * Charger le fichier de configuration de Spring * ApplicationContext est un conteneur IOC, qui a deux classes d'implémentation principales (ClassPathxmlapplicationContex le contexte * / applicationContext context = new ClassPathXmlApplicationContext ("ApplicationContext.xml"); // Helloworld hello1 = (helloworld) context.getBean ("Helloworld"); // Obtenez l'objet bean via id helloworld hello1 = context.getBean (helloworld.class); // obtenez l'objet bean par type (nécessite qu'il ne peut y avoir qu'un seul objet de ce type dans le conteneur IOC) System.out.println (hello1);} @ test (Car) context.getBean ("Car"); // Obtenez l'objet bean par type (nécessite qu'il ne peut y avoir qu'un seul objet de ce type dans le conteneur IOC) car1 = (car) context.getBean ("car1"); System.out.println (Car); System.out.println (car1); personne Person = (personne) context. 2. Vous trouverez ci-dessous la classe de test pour la collection
Newperson.java
Package com.spring.test.collections; import java.util.map; import com.spring.test.car; public class NewSerson {private String Name; private int Age; Map private <String, Car = "" Cars; public String getName () {Retour Name;} public Void setName (Nom de la chaîne) {this.name = new; Setage (int Age) {this.age = Âge;} Map public <String, car = ""> getCars () {return Cars;} public void setCars (map <String, car = "" Cars) {this.cars = Cars;} @ Override public String toString () {return "personne: [name =" + name + ", Âge =" + Age + ", Cars =" + Cars + ";;;;Personne.java
Package com.spring.test.collections; import java.util.list; import com.spring.test.car; public classe de classe {nom de chaîne privé;} public name; {this.age = age;} public list <Car> getCars () {return Cars;} public void setCars (list <Car> Cars) {this.cars = Cars;} @ Override public String toString () {return "Person: [name =" + name + ", Âge =" + Age + ", Cars =" + Cars + "]";}}DataSource.java
Package com.spring.test.collections; import java.util.properties; public classe DataSource {Propriétés privées Propriétés; Propriétés publiques GetProperties () {Return Properties;} public void setProperties (Properties Properties) {this.properties = Properties;} @ Overnide String Public Tostring () {return "Datasource: [Propriétés: "+ Propriétés +"] ";}}Main.java
package com.spring.test.collections; import org.junit.test; import org.springframework.context.applicationContext; import org.springframework.context.support.classpathxmlapplicationcontext; public class {@test public Void TestCollections () {applicationContext Context = new ClassPathxmlApplicationContext ("ApplicationContext.xml"); Person Person = (Person) context.getBean ("Person3"); System.out.println (Person); NewSerson NewSerson = (NewSerson) context.getBean ("NewPerson"); System.out.println (NewPerson); Datasource DataSource = (DataSource) context.getBean ("DataSource"); System.out.println (DataSource); personne personne4 = (personne) context.getBean ("Person4"); System.out.println (Person4); personne Person5 = (personne) context.getBean ("Person5"); System.out.println (Person5);}}Résumer
Ce qui précède est tout au sujet de l'exemple de la méthode d'injection de dépendance au cadre de printemps dans cet article, j'espère que cela sera utile à tout le monde. S'il y a des lacunes, veuillez laisser un message pour le signaler. Merci vos amis pour votre soutien pour ce site!