Перед прочтением этой статьи вы можете сначала ссылаться на статью « Понимание инъекции зависимости и инверсии контроля в весне » , чтобы узнать о соответствующем содержании инъекции зависимостей и инверсии контроля.
Три способа инъекции зависимостей
Внедрение свойств, введите значение свойства бобов с помощью метода сеттера или инъекции метода завода впрыска зависимых объектов (редко используется)
пример
Здесь мы используем Spring-4.3.2, файл конфигурации Maven
<dependency> <groupid>org.springframework</groupid> spring-core</artifactid> <version>${org.springframework-version}</version> <exclusions> <exclusion> <groupid>commons-logging</groupid> commons-logging</artifactid> </exclusion> </exclusions></dependency><dependency> <groupId> org.springframework </GroupId> Spring-Beans </artifactid> <sersion> $ {org.springframework-version} </version> </depervice> <dehyed> <groupd> org.springframe </groupd> spring-aop </artifactid> <sersion> $ {org.springframework-version} </version> </deperency> <dependency> <groupid> org.springframework </GroupId> Spring-Context </artifactid> <serse> $ {org.springframework-version} </версия> </зависимость> <Depoyed> <groupD> commons-log-log-log-log-log-log-log-log-log-log Commons-logging </artifactid> <sersion> 1.2 </version> </dependency> <!-junit-> <dehyederian> <groupid> junit </GroupId> junit </artifactid> <sersion> 3.8.1 </version> <cracpe> test </scope> </jependency>ApplicationContext.xml Файл конфигурации
<!-? xml version = "1.0" Encoding = "utf-8"?-> <beans xmlns = "https://www.springframework.org/schema/beans" xmlns: p = "https://ww.spramework.org/schema/p" xmlns: util = "https://www.springframework.org/schema/util" xmlns: xsi = "https://www.w3.org/2001/xmlschema-insstance" xsi: schemalocation = "https://wwww.springmema https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd "> infiepure. Класс: полное название класса бобов в контейнере и создать бон в контейнере IOC посредством отражения, поэтому класс бобов должен иметь конструктор параметров-> <bean id = "helloworld"> <name = "name" value = "crystal"> </свойство> </bean> <! <bean id = "car"> <constructor-arg index = "0" value = "bender"> </constructor-arg> <constructor-Arg index = "1" type = "double" value = "200000.0"> </constructor-arg> </bean> <bean id = "car1"> <, если лифта содержит специализированные символы, используйте <data attrata vivalta [! С значением дочерних узлов-> <constructor-arg type = "java.lang.string"> <dulch> <!-[cdata [<shanghai->]]> </value> </constructor-arg> <constructor-arg index = "1" type = "int" value = "200"> </constructor-arg> </bean> <bean em = "value =" 200 "> </constructor-arg> </bean> <bean =" value = "200" value = "crystal"> </property> <name = "age" value = "20"> </property> <!-Вы можете использовать ссылку для создания отношений между ссылками-> <!-<name = "car" ref = "car"> </property>-> <!-<name = "car"> <ref bean = "car2"/> </property>-> <!-<!-<! value = "changanfute"> </constructor-arg> <constructor-arg value = "3000000"> </constructor-arg> <constructor-arg value = "240"> </constructor-arg> </bean> </property>-> <!-Тестовое назначение null-> <!-<nome = vame = "<null/> </! ref = "car1"> </property> <!- назначить значения каскадным свойствам. ПРИМЕЧАНИЕ. Свойства должны быть инициализированы, прежде чем они могут присвоить значения для каскадных свойств. Они отличаются от Structs2-> <property name = "car.price" value = "400000"> </property> </bean> <!-Свойства сбора конфигурации теста-> <bean id = "person3"> <name = "name" value = "barry"> </property> <property name = "Age" value = "> </property> <prop name"> <Ref "> <Ref"> <Ref "> <Ref"> <Ref "> <Ref"> <Relect> <Relect> <Relect> <Relect> <Relect> <Relect> <Relect> <Relect> <Relect> <Relect> <Ref "> <Ref"> <Ref "> <Ref"> <Relect ". bean="car1"> <bean> <constructor-arg value="changanFute"></constructor-arg> <constructor-arg value="3000000"></constructor-arg> <constructor-arg value="240"></constructor-arg> </bean> </ref></ref></list> </property> </bean> <!-- Configure the property value of the Map--> <bean id="newPerson"> <property name="name" value="lina"></property> <property name="age" value="22"></property> <property name="cars"> <!-- Use map node and map entry child node to configure member variables of Map type --><map> <entry key="AA" value-ref="car"></entry> <entry key="BB" value-ref = "car1"> </inpit> </map> </property> </bean> <!-Настройка свойств Свойства-> <Bean Id = "DataSource"> <name = "Свойства"> <!-Использование реквизитов и детей для присвоения значений к свойствам. key = "jdbcurl"> jdbc: mysql: // test </prop> <prop key = "jdbcdriver"> com.mysql.jdbc.driver </prop> </props> </property> </bean> <!- Конфигурируйте Systeleton Collection Bean для справки с помощью нескольких Beans. Вам необходимо импортировать пространство имен UTIL-> <util: list id = "cars"> <ref bean = "car"> <ref bean = "car1"> </ref> </ref> </util: list> <bean id = "person4"> <name = "name" value = "Jackie"> </property> <name = "age" value = "30"> </value> <property> "arfot vame> </property". ref = "cars"> </property> </bean> <!-назначение значений свойствам бобов через пространство имен P, вам нужно сначала импортировать пространство P имен, что более кратко, чем традиционные методы конфигурации-> <Bean Id = "Person5" P: Age = "32" P: CARS-REF = "CARS" P: name = "Queue"> </bean> </beans> "cars" p: name = "Queue"> </bean> </bean
1. Ниже приведены простые инъекции атрибута и классы тестирования на инъекцию конструкции
Автомобиль. Ява
пакет com.spring.test; public class car {private String name; private int maxspeed; частная двойная цена; public car () {} public Car (String name, Double Price) {this.name = name; this.price = price;} public Car (String name, int maxspeed) {this.name = имя; {this.name = name; this.price = price; this.maxspeed = maxspeed;} public void setprice (двойная цена) {this.price = price;}@переопределить публичную строку tostring () {return "car [name:" + name + ", цена:" + ", maxspeed:" + maxspeed + "Helloworld.java
пакет com.spring.test; public class helloworld {private String name; public helloworld () {System.out.println ("Helloworld Constructor ...");} public String getName () {return name;} public void setName (String name) {System.out.println ("setName:" + name); toString () {return "hello," + name;}}Человек. Ява
пакет com.spring.test; public class person {private String name; private int age; public Car; public String getName () {return name;} public void setName (string name) {this.name = name;} public int getage () {return Age;} public void setage (int age) {this.age = age = age public car getCar () {return carecar (in vige); {this.car = car;}@переопределить публичную строку toString () {return "человек: [name =" + name + ", age =" + age + ", car =" + car + "]";}}Main.java
пакет com.spring.test; import org.junit.test; import org.springframework.context.applicationContext; import org.springframework.context.support.classpathxmlapplicationContext; public wear {public void main (string [] args) {halloworld hello = new. Helloworld (); hello.setname ("barry"); system.out.println ("print:" + hello + "/n"); // Загрузить файл конфигурации пружины/*** Загрузить файл конфигурации пружины* ApplicationContext - это контейнер IOC, который имеет два основных класса реализации ClassPathxmlApplicationContextectextextextextextectextextectextextectextectextextextextextectextextextextextextextectextectextectextextextextextext. Инициализация контекста */applicationContext context = new ClassPathxMlapplicationContext ("applicateContext.xml"); // helloworld hello1 = (helloworld) context.getbean ("helloworld"); // Получить объект Bean через id helloworld hello1 = context.getbean (helloworld.class); // Получить объект Bean по типу (требует, чтобы был только один объект этого типа в контейнере IOC) System.out.println (hello1);}@test public void -testcontructor () {ApplicationContextectextextextectretcrocecontextcrolctectrectroctectrectrectrectrectrectrectroctroctorceclectroctroctorcecluctroctor (). car = (car) context.getbean ("car"); // Получить объект Bean по типу (требует, чтобы в контейнере IOC CAR1 (CAR) может быть только один объект CAR CAR1 = (CAR). context.getbean ("person"); System.out.println (человек);}} 2. Ниже приведен тестовый класс для коллекции
Newperson.java
пакет com.spring.test.collections; import java.util.map; import com.spring.test.car; public class newperson {private String name; Private int age; частная карта <string, car = "> cars; public String getName () {return name;} public void setName (String name) {name = ineame; STAGE (int age) {this.age = age;} public map <string, car = ""> getCars () {return cars;} public void setcars (map <string, car = "> cars) {this.cars = cars;}@переопределить публичные строки toString () {return": [name = " + name +", age = " +", arstring = ")")Человек. Ява
пакет com.spring.test.collections; import java.util.list; import com.spring.test.car; Public Class Person {private String name; private int age; public list <Car> cars; public String getName () {return name;} public void setName (строковое имя) {this.name = name; public inte getage () {return Age; {this.age = age;} public list <Ar> getCars () {return cars;} public void setCars (list <Arz> cars) {this.cars = cars;}@переопределить публичные строки toString () {return "человек: [name =" + name + ", age =" + ", cars =" + carse + "]";}}}}}}}}}DataSource.java
пакет com.spring.test.collections; import java.util.properties; public class dataSource {Private Properties Properties; Public Properties getProperties () {return Properties;} public void setProperties (Properties Properties) {this.properties = wisperties {return Tosstries) [Свойства: " + свойства +"] ";}}Main.java
пакет com.spring.test.collections; import org.junit.test; import org.springframework.context.applicationContext; import org.springframework.context.support.classpathxmlapplicationcontext; public class main {@test public void -testcollections () {applicateContext = context = context = New ClassPathxMlapplicationContext ("ApplicationContext.xml"); Person Person = (person) context.getbean ("person3"); System.out.println (Person); Newperson newperson = (newperson) context.getbean ("newperson"); System.out.println (newperson); DataSource dataSource = (dataSource = dataSource = (dataSource = (dataSource = (dataSource = (datasource = (dataSource = (dataSource = (dataSource = (dataSource); context.getbean ("dataSource"); System.out.println (dataSource); Person Person4 = (Person) context.getbean ("person4"); System.out.println (Person4); Person Person5 = (Person).Суммировать
Выше приведено примером метода впрыскивания зависимости Spring Framework в этой статье, я надеюсь, что это будет полезно для всех. Если есть какие -либо недостатки, пожалуйста, оставьте сообщение, чтобы указать это. Спасибо, друзья, за вашу поддержку на этом сайте!