Spring(四)依赖注入的三种方式

Spring学习笔记(四)

一、依赖注入的三种方式

1.构造器注入

  构造器方法注入简单来说就是通过对象的构造方法来进行注入,只要在对应实体类中创建相应的构造方法,这里有个坑,java默认的构造方法是无参数的,如果你写了一个有参数的构造方法,默认的就相当于被忽略了,所以如果你想还行继续使用无参数的构造方法,就在写一个就可以了!比如:

public class Person {
    
    
		private String name;
		private int age;
		Person(String s,int a){
    
    
			this.name=s;
			this.age=a;	
	}
		Person(){
    
    
				
	}
}

  相应的Spring配置文件为:

<!--如果没有index索引,<constructor-age>的构造顺序和构造方法的顺序一致-->
<bean id="person" class="entity.Person">
<constructor-age value="张三" index="0"/>
<constructor-age value="18" index="1"/>
</bean>
<!--或者用name的方式->
<bean id="person" class="entity.Person">
<constructor-age name="name" value="张三" />
<constructor-age name="age" value="18" />
</bean>

2.setter设值注入

  setter设值注入就是用对象的set方法来进行注入。比如:

public class Person {
    
    
		private String name;
		private int age;
		public void setName(String name) {
    
    
			this.name = name;
		}		
		public void setAge(int age) {
    
    
			this.age = age;
		}		
}

这就是实体类Person的两个set方法,然后通过spring配置文件applicationContext:

bean id="person" class="entity.Person">
	<property name="name" value="李帅"></property>
	<property name="age" value="29"></property>
</bean>	
<bean id="course" class="entity.Course">
	<property name="courseName" value="Java"></property>
	<property name="courseHours" value="64"></property>
	<property name="person" ref="person"></property>
</bean>	

  采用value或者ref来给对象的属性赋值,对象一定要有相应的set方法,否则就会抛出异常。

3.p命名空间的注入

  p命名空间注入的特点是使用属性而不是子元素的形式配置Bean的属性,从而简化了配置代码。使用前要在spring配置文件中引入p命名空间:

xmlns:p=“http://www.springframework.org/schema/p”

  p命名空间简单来讲就是使用p命名空间来给属性赋值,直接在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"
	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">
使用p命名空间:
	<bean id="course" class="entity.Course"
	p:courseName="数学"
	p:courseHours="12"
	p:person-ref="person">
	<!-- p:属性名-ref:给非简单类型赋值,这里是person对象类型-->
	
</bean>	

猜你喜欢

转载自blog.csdn.net/qq_46046423/article/details/114623645