Spring 简单使用IoC与DI——XML配置

目录


Spring简介

导入jar包

Spring配置文件

Spring的IoC

IoC简介

快速使用IoC

Spring创建对象的三种方式

使用构造方法

使用实例工厂

使用静态静态工厂

Spring注入的两种方式

使用构造方法注入

使用setter方式注入

setter方式多种数据类型的注入

Spring DI介绍


Spring简介

  Spring框架可以将其他技术融合在一起工作,类似于一种胶水。

  Spring最重要的核心:IoC(DI)、AOP、声明式事务管理

  这里只介绍Spring的相关用法,不会深入探讨底层原理或者接口实现。

导入jar包

  Spring对于每一个部分的功能,都单独有一个jar包,但是多数jar包之间都是相互依赖的,所以,为了解决不必要的麻烦,初期阶段可以导入所有的Spring jar包。

  另外,Spring框架还需要commons-logging、log4J的功能支持,所以还需要导入commons-logging、log4J的jar包。

  如果涉及到数据库操作,还需要额外导入jdbc-mysql驱动jar包

  如果需要集成mybatis,则还需要导入mybatis-spring的jar包。

Spring配置文件

  Spring的配置文件是一个xml文件,文件名随意,配置文件可以存放在src目录下,或者src下的某个专门存放配置文件的目录中。

  我这里使用的是:在src创建一个config目录,然后创建spring配置文件,文件名为applicationContext.xml。

  spring的配置文件使用xml格式,mybatis框架的配置文件也是xml格式,但是mybatis配置文件中使用的是一种dtd,Spring配置文件中使用较为高级的xsd。

  一个简单的spring配置文件模板如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
   
	<bean></bean>
   
</beans>

  上面的xmlns,其实是XML namespace的缩写,即XML命名空间,需要Spring的某个功能的时候,只需要添加对应的xmlns,然后指定xsd即可。

  比如上面的配置文件只有最基本的spring-beans功能,如果要使用aop,则可以这样做:

<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

</bean>

  

Spring的IoC

  IoC简介

  IoC(Inversion of Control),控制反转。

  分为两个部分,分别是:

  1、控制:控制类的实例化对象;

  2、反转:将程序员手动操作转交给Spring负责。

·  IoC的功能就是:将以前由程序员手动创建对象的过程,转交给Spring来完成。

  

  快速使用IoC

  创建实体类 cn.ganlixin.pojo.Person.java

package cn.ganlixin.pojo;

public class Person {
	private int id;
	private String name;
	private int age;
	// 省略了有参构造方法、无参构造方法、getter、setter、toString方法
}

  

  如果不使用Spring框架,创建Person类的对象,最简单的方式可以这样做:

package cn.ganlixin.test;

import cn.ganlixin.pojo.Person;

public class Test {
	public static void main(String[] args) {
		Person person = new Person();
		System.out.println(person); // Person [id=0, name=null, age=0]
	}
}

  当然,创建对象不是只有new这一种方式,其他方式,比如工厂模式(实例工厂和静态工厂)都能创建对象。

  如果要使用Sping,首先编辑spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
	<!-- 默认使用的是无参构造器 -->
	<bean id="person" class="cn.ganlixin.pojo.Person"></bean>
	
</beans>

  

  测试Spring使用IoC创建对象:

package cn.ganlixin.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.ganlixin.pojo.Person;

public class Test {
	public static void main(String[] args) {
		
		// 利用spring的配置文件,创建ApplicationContext对象
		ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
		
		// 通过applicationContext对象的getBean()方法可以获取由Spring创建的对象
		// 第一个参数是Spring配置文件中bean标签的id,第二个参数是设置返回对象的类型
		Person person = ac.getBean("person", Person.class);
		System.out.println(person); // Person [id=0, name=null, age=0]
		
	}
}

  到这里,已经看到Spring的IoC了,虽然只是一个很简单的person对象创建。

Spring创建对象的三种方式

  就我们平时创建对象,就可以举出三种方式:

  1、new关键字(使用构造方法创建对象)

  2、实例工厂

  3、静态工厂

  同样地,针对上面的每一种方式,利用Spring框架也可以实现。

  使用构造方法创建对象

  平时,我们使用new关键字来创建对象的时候,调用的是构造方法,可以分为无参构造方法和有参构造方法,而有参构造方法又可以重载。

  使用Spring来创建对象的时候,可以有两种方式:

  1、默认调用的是无参构造方法

<!-- 默认使用的是无参构造器 -->
<bean id="person" class="cn.ganlixin.pojo.Person"></bean>

  

  2、调用有参构造方法来创建对象:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
	<!-- 使用有参构造方法 -->
	<bean id="person" class="cn.ganlixin.pojo.Person">
		<!-- <constructor-arg index="" name="" type="" value="" ref=""></constructor-arg> -->
		<constructor-arg index="0" value="123"></constructor-arg>
		<constructor-arg index="1" value="demo"></constructor-arg>
		<constructor-arg index="2" value="99"></constructor-arg>
	</bean>
</beans>

  上面的constructor-arg标签有多个属性,分别是index、name、type、value、ref,他们的含义表示的是:

  1、index:为构造方法的第index+1个参数赋值,index从0开始计数。

  2、name:构造方法的参数的名称

  3、type:构造方法参数的类型

  4、value:如果构造方法的参数是基本数据类型(包括String),则用value赋值。

  5、ref:如果构造方法的参数是引用类型(对象),则需要使用ref属性。

  上面几个属性,通过index、name、type这三个属性共同作用,完全可以确定调用哪一个构造方法,当然并不是每一个属性都要设置。

  如果没有将index、name、type都设置(设置了1个或者2个属性),导致出现可以匹配多个构造方法,此时,就会调用类中后面一个构造方法。

  通过构造方法来创建对象是Spring的一种注入方式,另外一种是使用setter方法时注入。

  使用实例工厂方法来创建对象

  使用实例工厂方式,我们必须先创建一个工厂,以上面的Person为例,创建cn.ganlixin.factory.PersonFactory.java:

package cn.ganlixin.factory;

import cn.ganlixin.pojo.Person;

public class PersonFactory {
	public Person getInstance() {
		return new Person();
	}
}

  修改Spring配置文件:

<!-- 创建person工厂bean -->
<bean id="personFactory" class="cn.ganlixin.factory.PersonFactory"></bean>

<!-- 调用指定工厂(factory-bean)的指定方法(factory-method)来创建对象 -->
<bean id="person" factory-bean="personFactory" factory-method="getInstance"></bean>

  

  使用静态工厂来创建对象

  使用静态工厂,同样需要创建静态工厂,并且定义一个静态方法返回对象:

package cn.ganlixin.factory;

import cn.ganlixin.pojo.Person;

public class PersonFactory {
	public static Person getInstance() {
		return new Person();
	}
}

  修改Spring的配置文件:

<!-- 调用指定工厂类的指定方法 -->
<bean id="person"  class="cn.ganlixin.factory.PersonFactory" 
	  factory-method="getInstance"></bean>

  

Spring注入

  注入(Inject),这个词的意思:创建对象的时候,为对象的属性设置值,这个过程或者说这个动作就叫做注入。

  而为对象的属性赋值,有两种方式:

  1、调用构造方法(有参和无参构造方法)

  2、使用setter方式

  使用构造方法注入

  使用构造方法注入,如果是有参构造方法,则是使用constructor-arg标签,通过设置index、name、type、value、ref来为属性赋值。

  参考上面的内容:前往

  使用setter方式注入

   使用setter方式注入,首先需要我们创建对象的类,为属性创建了setter方法,否则使用setter方式进行注入就会失败,因为setter方式注入就是调用setter方法。使用setter方式注入的时候,会首先调用无参构造方法,然后调用setter方法进行注入。

   setter方式注入使用的property标签

<bean id="person" class="cn.ganlixin.pojo.Person">
	<property name="id" value="1"></property>
	<!-- 等价于
	<property name="id">
		<value>1</value>
	</property>
	-->
	<property name="name" value="abc"></property>
	<property name="age" value="88"></property>
</bean>

  

  setter方式多种数据类型的注入

  创建Student实体类,包含各种数据类型的属性:

package cn.ganlixin.pojo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Student {
	private int id;
	private String name;
	private boolean gender;
	private String[] hobbies;
	private List<String> language;
	private Map<String, Integer> score;
	private Set<String> book;
	private Properties properties;
	// 省略了有参构造方法、无参构造方法、getter、setter、toString方法
}

  

  修改Spring配置文件:

<bean id="student" class="cn.ganlixin.pojo.Student">
	<property name="id" value="1"></property>
	<property name="name" value="test999"></property>
	<property name="gender" value="true"></property>
	<property name="hobbies">
		<array>
			<value>basketball</value>
			<value>swimming</value>
		</array>
	</property>
	<property name="language">
		<list>
			<value>Java</value>
			<value>PHP</value>
		</list>
	</property>
	<property name="score">
		<map>
			<entry key="english" value="99"></entry>
			<entry key="math" value="100"></entry>
			<!-- <entry key-ref="" value-ref=""></entry> -->
		</map>
	</property>
	<property name="book">
		<set>
			<value>Think In Java</value>
			<value>Effective Java</value>
		</set>
	</property>
	<property name="properties">
		<props>
			<prop key="prop1">prop1Value</prop>
			<prop key="prop2">prop2Value</prop>
		</props>
	</property>
</bean>

  测试:

package cn.ganlixin.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.ganlixin.pojo.Student;

public class Test {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
		Student student = ac.getBean("student", Student.class);
		System.out.println(student);
		/*
		Student [
			id=1, 
			name=test999, 
			gender=true, 
			hobbies=[basketball, swimming], 
			language=[Java, PHP], 
			score={english=99, math=100}, 
			book=[Think In Java, Effective Java], 
			properties={prop2=prop2Value, prop1=prop1Value}
		]
		 */
	}
}

  

Spring DI介绍

  DI(Dependency Injection),依赖注入。

  先看下面有两个类,再说依赖注入的含义:

package cn.ganlixin.pojo;

public class A {
	private String name;
	// 省略了有参构造方法、无参构造方法、getter、setter、toString方法
}

  

package cn.ganlixin.pojo;

public class B {
	private String name;
	private A a;  // B类中有一个属性是A类的对象
	
	// 省略了有参构造方法、无参构造方法、getter、setter、toString方法
}

  

  依赖,在软件工程中是一个很常见的概念,可以理解为:需要一个、有一个。以上面的A类和B类为例:B类中有一个属性,是A类的对象,此时可以理解为B依赖A:

  注入,就是为属性赋值,以A类和B类的关系,依赖注入:为B类对象中的  A类对象属性 赋值。

  调用setter方法注入的过程也就是:bb.setA(aa)。

<bean id="aa" class="cn.ganlixin.pojo.A">
	<property name="name" value="aValue"></property>
</bean>

<bean id="b" class="cn.ganlixin.pojo.B">
	<property name="name" value="bValue"></property>
	<!-- 通过ref引用另外一个bean -->
	<property name="a" ref="aa"></property>
</bean>	

  看了上面的配置,其实DI特别好理解,也就是类的属性是一个引用,在注入的时候使用ref,引用另外一个bean。

原文地址:https://www.cnblogs.com/-beyond/p/10476172.html