Example of the Spring framework dependency injection approach

  • 2020-11-18 06:12:07
  • OfStack

Before reading this article, you may want to refer to understanding DEPENDENCY Injection and INVERSION of Control in Spring 1 for an overview of dependency injection and INVERSION of Control.

There are three ways of dependency injection

Attribute injection, using setter methods to inject bean attribute values or dependent objects to construct injection factory method injection (rarely used)
example

Here we used the spring-4.3.2, maven configuration file


<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>
 <version>${org.springframework-version}</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 spring-aop</artifactid>
 <version>${org.springframework-version}</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 spring-context</artifactid>
 <version>${org.springframework-version}</version>
</dependency>
<dependency>
 <groupid>commons-logging</groupid>
 commons-logging</artifactid>
 <version>1.2</version>
</dependency>
<!-- Junit -->
<dependency>
 <groupid>junit</groupid>
 junit</artifactid>
 <version>3.8.1</version>
 <scope>test</scope>
</dependency>

applicationContext.xml configuration file


<!--?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:schemalocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
  https://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
 
 <!-- 
   configuration bean
  id : Identifies the container bean object 
  class : bean Full class name, by reflection in IOC Create in container Bean , so it is required that Bean Classes must have no reference constructors 
  -->
 <bean class="com.spring.test.HelloWorld" id="helloWorld">
  <property name="name" value="crystal"></property>
 </bean>
 
 <!--  Configuration by constructor bean, You can specify the location and type of arguments to distinguish overloaded constructors  -->
 <bean class="com.spring.test.Car" id="car">
  <constructor-arg index="0" value="BENCHI"></constructor-arg>
  <constructor-arg index="1" type="double" value="200000.0"></constructor-arg>
 </bean>
 <bean class="com.spring.test.Car" id="car1">
  <!--  If the literal contains special characters, use <![CDATA[]]> wrapped 
    Property values can be used value Child nodes to configure 
   -->
  <constructor-arg type="java.lang.String">
   <value><!--[CDATA[<shanghai-->]]></value>
  </constructor-arg>
  <constructor-arg index="1" type="int" value="200"></constructor-arg>
 </bean>
 
 <bean class="com.spring.test.Person" id="person">
  <property name="name" value="Crystal"></property>
  <property name="age" value="20"></property>
  <!--  You can use ref Establish relationships between references  -->
  <!-- 
  <property name="car" ref="car"></property>
   -->
  <!-- 
   <property name="car">
    <ref bean="car2"/>
   </property>
   -->
   <!-- 
   <property name="car">
   <bean class="com.spring.test.Car">
    <constructor-arg value="changanFute"></constructor-arg>
    <constructor-arg value="3000000"></constructor-arg>
    <constructor-arg value="240"></constructor-arg>
   </bean>
   </property> 
   -->
   <!--  The test assignment null -->
   <!-- <property name="car"><null/></property> -->
   <property name="car" ref="car1"></property>
   <!--  For a cascading property, note: the property needs to be initialized before it can be assigned to a cascading property, and structs2 different  -->
   <property name="car.price" value="400000"></property>
 </bean>
 
 <!--  Test the configuration set properties  -->
 <bean class="com.spring.test.collections.Person" id="person3">
  <property name="name" value="barry"></property>
  <property name="age" value="21"></property>
  <property name="cars">
   <list>
    <ref bean="car">
    <ref bean="car1">
    <bean class="com.spring.test.Car">
     <constructor-arg value="changanFute"></constructor-arg>
     <constructor-arg value="3000000"></constructor-arg>
     <constructor-arg value="240"></constructor-arg>
    </bean>
   </ref></ref></list>
  </property>
 </bean>
 
 <!--  configuration Map The attribute value  -->
 <bean class="com.spring.test.collections.NewPerson" id="newPerson">
  <property name="name" value="lina"></property>
  <property name="age" value="22"></property>
  <property name="cars">
   <!--  use map Nodes and map the entry Child node configuration Map A member variable of type  --><map>
    <entry key="AA" value-ref="car"></entry>
    <entry key="BB" value-ref="car1"></entry></map>
  </property>
 </bean>
 
 
 <!--  configuration Properties Attribute values  -->
 <bean class="com.spring.test.collections.DataSource" id="dataSource">
  <property name="properties">
   <!--  use props and prop The child node is Properties Attribute assignment  -->
   <props>
    <prop key="user">root</prop>
    <prop key="password">1234</prop>
    <prop key="jdbcUrl">jdbc:mysql://test</prop>
    <prop key="jdbcDriver">com.mysql.jdbc.Driver</prop>
   </props>
  </property>
 </bean>
 
 <!--  A collection of distribution singletons bean For more than one bean To reference, you need to import util The namespace  -->
 <util:list id="cars">
  <ref bean="car">
  <ref bean="car1">
 </ref></ref></util:list>
 
 <bean class="com.spring.test.collections.Person" id="person4">
  <property name="name" value="Jackie"></property>
  <property name="age" value="30"></property>
  <property name="cars" ref="cars"></property>
 </bean>
 
 <!--  through p The namespace is bean Attribute assignment, which requires a pilot entry p Namespaces are simpler than traditional configurations  -->
 <bean class="com.spring.test.collections.Person" id="person5" p:age="32" p:cars-ref="cars" p:name="Queue"></bean>
</beans>

1. The following is a simple property injection, construct the injected test class

Car.java


package com.spring.test;
public class Car {
	private String name;
	private int maxSpeed;
	private double price;
	public Car() {
	}
	public Car(String name, double price) {
		this.name = name;
		this.price = price;
	}
	public Car(String name, int maxSpeed) {
		this.name = name;
		this.maxSpeed = maxSpeed;
	}
	public Car(String name, double price, int maxSpeed) {
		this.name = name;
		this.price = price;
		this.maxSpeed = maxSpeed;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	 public String toString() {
		return "Car [name:" + name + ", price:" + price + ", maxSpeed:" + maxSpeed + "]";
	}
}

HelloWorld.java


package 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);
		this.name = name;
	}
	@Override
	 public String toString() {
		return "hello," + name;
	}
}

Person.java


package com.spring.test;
public class Person {
	private String name;
	private int age;
	private Car 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;
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
	@Override
	 public String toString() {
		return "Person: [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(String[] args) {
		HelloWorld hello = new HelloWorld();
		hello.setName("barry");
		System.out.println("print:"+ hello + "\n");
		//  loading  Spring  The configuration file 
		/**
   *  loading  Spring  The configuration file 
   * ApplicationContext is IOC Container, which has two main implementation classes ( ClassPathXmlApplicationContext and FileSystemXmlApplicationContext ) 
   * ApplicationContext All singletons are instantiated when the context is initialized Bean
   */
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//HelloWorld hello1 = (HelloWorld) context.getBean("helloWorld"); //  through id To obtain bean object 
		HelloWorld hello1 = context.getBean(HelloWorld.class);
		//  Get by type bean Object (required in IOC Objects of that type in the container can only have 1 A) 
		System.out.println(hello1);
	}
	@Test
	 public void testContructor() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		Car car = (Car) context.getBean("car");
		//  Get by type bean Object (required in IOC Objects of that type in the container can only have 1 A) 
		Car car1 = (Car) context.getBean("car1");
		System.out.println(car);
		System.out.println(car1);
		Person person = (Person) context.getBean("person");
		System.out.println(person);
	}
}

2. Below is the test class for the collection
NewPerson.java


package com.spring.test.collections;
import java.util.Map;
import com.spring.test.Car;
public class NewPerson {
	private String name;
	private int age;
	private Map<string, car=""> cars;
	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;
	}
	public Map<string, car=""> getCars() {
		return cars;
	}
	public void setCars(Map<string, car=""> cars) {
		this.cars = cars;
	}
	@Override
	 public String toString() {
		return "Person: [name=" + name + ", age=" + age + ", cars=" + cars + "]";
	}
}

Person.java


package com.spring.test.collections;
import java.util.List;
import com.spring.test.Car;
public class Person {
	private String name;
	private int age;
	private List<car> cars;
	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;
	}
	public List<car> getCars() {
		return cars;
	}
	public void setCars(List<car> cars) {
		this.cars = cars;
	}
	@Override
	 public String toString() {
		return "Person: [name=" + name + ", age=" + age + ", cars=" + cars + "]";
	}
}

DataSource.java


package 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 = properties;
	}
	@Override
	 public String toString() {
		return "DataSource: [properties:" + properties + "]";
	}
}

Main.java


package 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() {
		ApplicationContext 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) context.getBean("dataSource");
		System.out.println(dataSource);
		Person person4 = (Person) context.getBean("person4");
		System.out.println(person4);
		Person person5 = (Person) context.getBean("person5");
		System.out.println(person5);
	}
}

conclusion

That's it for this article's example of the Spring framework dependency injection approach, and I hope you found it helpful. If there is any deficiency, please let me know. Thank you for your support!


Related articles: