Views on several methods of dependency injection in spring

Posted by daok on Sat, 08 Feb 2020 09:18:21 +0100

Views on several methods of dependency injection in spring

IOC(inversion of Control):

It is an inversion of the direction in which resources are acquired by the container that actively provides the resources acquired by the component, rather than being created by the container itself.All the component has to do is choose a way to receive this resource.

DI(Dependency injection):

Components accept injection of resources from containers in well-defined ways, such as setter methods
Self-perceived as a mechanism of reflection.

Injection Demo

ioc:

2: Configure bean s

xml file-based injection

Some of the bean s'considerations and details are presented in code:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<!-- Configure one bean -->
	<bean id="helloWorld" class="com.liusir.beans.HelloWorld">
		
	</bean>
	
	<!-- Configure one bean -->
	<bean id="helloWorld2" class="com.liusir.beans.HelloWorld">
		<!-- Assigning values to attributes -->
		<!-- Injection through attributes: adopt setter Method Injection Property Value -->
		<property name="user" value="Tom"></property>
	</bean>
	
	<!-- Injecting attribute values through a constructor -->
	<bean id="helloWorld3" class="com.liusir.beans.HelloWorld">
		<!-- Requirement: stay Bean There must be a corresponding constructor in.  -->
		<constructor-arg value="Mike"></constructor-arg>
	</bean>
	
	<!-- If one bean There are multiple constructors, How to use a constructor to bean Attribute assignment of -->
	<!-- According to the index and value More accurate positioning. (understand) -->
	<bean id="car" class="com.liusir.beans.Car">
		<constructor-arg value="KUGA" index="1"></constructor-arg>
		<constructor-arg value="ChangAnFord" index="0"></constructor-arg>
		<constructor-arg value="250000" type="float"></constructor-arg>
	</bean>
	
	<bean id="car2" class="com.liusir.beans.Car">
		<constructor-arg value="ChangAnMazda"></constructor-arg>
		<!-- If the literal value contains special characters, Then you can use DCDATA To assign values. (understand) -->
		<constructor-arg>
			<value><![CDATA[<ATARZA>]]></value>
		</constructor-arg>
		<constructor-arg value="180" type="int"></constructor-arg>
	</bean>
	
	<!-- To configure bean -->
	<bean id="dao5" class="com.liusir.ref.Dao"></bean>

	<bean id="service" class="com.liusir.ref.Service">
		<!-- adopt ref Property value specifies which current property is pointing to bean! -->
		<property name="dao" ref="dao5"></property>
	</bean>
	
	<!-- Declare Use Internal bean -->
	<bean id="service2" class="com.liusir.ref.Service">
		<property name="dao">
			<!-- inside bean, Similar to anonymous internal class object. Cannot be external bean To reference, And it's not necessary to set it up id attribute -->
			<bean class="com.liusir.ref.Dao">
				<property name="dataSource" value="c3p0"></property>
			</bean>
		</property>
	</bean>

	<bean id="dao2" class="com.liusir.ref.Dao">
		<!-- by Dao Of dataSource Attribute assignment null, If one bean Property value of is not null, You need to set it to null(understand) -->
		<property name="dataSource"><null/></property>
	</bean>
	
	<!-- Assembly Set Properties -->
	<bean id="user" class="com.liusir.beans.User">
		<property name="userName" value="Jack"></property>
		<property name="cars">
			<!-- Use list Element to assemble collection attributes -->
			<list>
				<ref bean="car"/>
				<ref bean="car2"/>
			</list>
		</property>
	</bean>
	
	<!-- Declare set type bean -->
	<util:list id="cars">
		<ref bean="car"/>
		<ref bean="car2"/>
	</util:list>
	
	<bean id="user2" class="com.liusir.beans.User">
		<property name="userName" value="Rose"></property>
		<!-- Referencing an externally declared list -->
		<property name="cars" ref="cars"></property>
	</bean>
	
	<bean id="user3" class="com.liusir.beans.User"
		p:cars-ref="cars" p:userName="Titannic"></bean>
		
	<!-- bean Is the configuration inheritable ? Use parent To complete inheritance -->	
	<bean id="user4" parent="user" p:userName="Bob"></bean>
	
	<bean id="user6" parent="user" p:userName="Victoria"></bean>
	
	<!-- test depents-on -->	
	<bean id="user5" parent="user" p:userName="Backham" depends-on="user6"></bean>
	
	<util:properties>
	    <prop key="liusir" >
	    </prop>
	
	</util:properties>
	
      <!--Used by util The independent part can be repeated beans Shared in  -->
      <util:map>
      <entry key="liusir" value-ref="car1"></entry>
      <entry key="liudi" value-ref="car2"></entry>
      </util:map>
      
      <util:properties>
          <prop key="name"> liusir</prop>
          <prop key="user">lsiduf</prop>
      </util:properties>
</beans>

Need to instantiate in spring in ioc container

: ApplicationContext

//1. Create Spring's IOC container
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		
		//2. Get an instance of a bean from an IOC container
		HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld3");

The methods to get bean s in the ioc container are

There are two ways to inject

The first is attribute injection

The second is constructor injection

The details of the injection have been presented in the xml file-based injection code above

--------------------------------------------------------------

Questions about using auto-exclusive in xml configurations

First point: byType

Second point: byName

--------------------------------------------------------------

Configuration of inherited bean s

 <bean id="car" class="com.liusir.autowire.Car">
	   <property name="company" value="aodi"></property>
	   <property name="brand" value="beijing"></property>
	   <property name="maxSpeed" value="240"></property>
	   <property name="price" value="50000"></property>
   </bean>
   <!--Inheritance is equivalent to attributes being attributed to and overridden  -->
   <bean id="user"  abstract="true">
        <property name="name" value="liudi" ></property>
   </bean>
   
   <bean id="user2" autowire="byType" class="com.liusir.extend.User" parent="user">
   
   </bean>
   

-------------------------------------------------------------

Use external property files

<context:property-placeholder location="classpath:db.properties"/>
  
   <!-- Configure Data Source -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		
		<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>
   

--------------------------------------------------------------------------------

Injection by factory method

First: Static factory method

bean class:

package com.liusir.Factory;

import java.util.HashMap;
import java.util.Map;

public class staticFactory {

	
private static Map<String,Car> cars=new HashMap<>();
	
	static {
		cars.put("audi",new Car("audi",30000.0f));
		cars.put("baoma", new Car("baoma",40000.f));
	}
	
	
	public static Car getcar(String name) {
		
		return cars.get(name);
		
	}
}

xml configuration file:

<!-- Static Factory Method -->
<bean id="car" class="com.liusir.Factory.staticFactory" factory-method="getcar">
  <constructor-arg value="audi"></constructor-arg>
</bean>

Second instance factory method

bean class

package com.liusir.Factory;

import java.util.HashMap;
import java.util.Map;

public class InstanceFactory {

	private Map<String, Car> cars = null;

	public InstanceFactory() {
		cars = new HashMap<>();
		cars.put("audi", new Car("audi", 30000.0f));
		cars.put("baoma", new Car("baoma", 40000.f));
	}
	public Car getcar(String name) {
		
		return cars.get(name);
		
	}

}

xml configuration file:

<!-- Configure Factory Instance -->
<bean id="instanceFactory" class="com.liusir.Factory.InstanceFactory" ></bean>

<!-- Instance factory method configuration bean -->
<bean id="car2"  factory-bean="instanceFactory" factory-method="getcar">
   <constructor-arg value="baoma"></constructor-arg>
</bean>

The third is factorybean

bean class:

package com.liusir.Factory;

import org.springframework.beans.factory.FactoryBean;

public class CarFactoryBean implements FactoryBean{

	private String brand;
	
	public void setBrand(String brand) {
		this.brand = brand;
	}
	@Override
	public Car getObject() throws Exception {
		return new Car(brand,500000f);
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return Car.class;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return true;
	}

}

Configuration of xml file:

<!-- adopt factorybean To configure -->

<bean id="car3" class="com.liusir.Factory.CarFactoryBean">
<property name="brand" value="BWM"></property>
</bean>

The fourth is generic dependency injection

Details used are

<context:component-scan base-package="com.liusir.annotation" 
		> </context:component-scan> 

A few of the details behind it

Explain with source code:

<!-- exclude-filter:Child node specifies to exclude those specified expression components -->
	<!-- include-filter:Expression specifies which expression groups to include use-default-filters Use together -->
	<!-- 
	<context:component-scan
		base-package="com.liusir.annotation" use-default-filters="false">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Respository" />
		 -->
		<!-- 
		<context:include-filter type="annotation"
		 expression="com.liusir.annotation.Controllar.ControllerTest" /> 
		 -->
		 <!-- 
		<context:include-filter type="assignable"
		 expression="com.liusir.annotation.Controllar.ControllerTest" /> 
		 -->

@autowired auto-assembly

package com.liusir.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.liusir.annotation.Controllar.ControllerTest;

//automatic assembly
/*
 * bean Linkage: There are two ways 
 *  >Use Autowired: If there are multiple bean s, keep property names consistent
 *  >With Autowired Qualifiter: is the name of the bean
 */
@Component
public class ObjectTest {

	@Autowired
	@Qualifier("controllerTest")
	private ControllerTest controllerTest;
	
	public void test() {
		controllerTest.test();
	}
	
}

This is injected through annotations and generics

Published an original article. Praise 0. Visits 6
Private letter follow

Topics: xml JDBC Spring Attribute