Spring特性--DI
DI:Dependency Injection(依赖注入),通俗的讲就是一种通过xml配置文件,为交给sping容器的对象初始化参数。又称做控制反转:Inversion of Control(IoC)
依赖注入主要分为四种形式:
|-:基于构造方法的依赖注入
|-:基于setter方法的依赖注入
|-:基于工厂的注入
|-:基于泛型的注入
基于构造方法的依赖注入又可以分为以下几种:
·复杂数据类型:
·简单数据类型:
|- 基于属性类型(type)
|-基于索引(index)
|-基于参数名称(name)
复杂数据类型实例
package com.fuwh.spring; /*
* POJO类
*/
public class Clazz { private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
} }
package com.fuwh.spring;
/*
* POJO类
*/
public class Lesson { private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
} }
package com.fuwh.spring; public class Student { private Clazz clazz;
private Lesson lesson; public Student(Clazz clazz, Lesson lesson) {
this.clazz = clazz;
this.lesson = lesson;
} @Override
public String toString() {
return "Student [clazz=" + clazz.getGrade()+clazz.getName() + ", lesson=" + lesson.getName()+","+lesson.getScore() + "学分]";
} } <?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="student" class="com.fuwh.spring.Student" lazy-init="default">
<constructor-arg ref="clazz"/>
<constructor-arg ref="lesson"/>
</bean> <bean id="clazz" class="com.fuwh.spring.Clazz">
<property name="name" value="信本"/>
<property name="grade" value="08"/>
</bean>
<bean id="lesson" class="com.fuwh.spring.Lesson">
<property name="name" value="java"/>
<property name="score" value="4"/>
</bean>
</beans> package com.fuwh.spring; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Spring01 { public static void main(String[] args) {
/*
* 测试类
*/
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
System.out.println(ac.getBean("student",Student.class));
}
}
基于属性类型(type) 实例:
package com.fuwh.spring;
/*
* POJO类
*/
public class Clazz { private String name;
private int grade; public Clazz(String name, int grade) {
super();
this.name = name;
this.grade = grade;
}
@Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
} }
<?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"> <!-- spring配置文件 -->
<bean id="clazz" class="com.fuwh.spring.Clazz" lazy-init="default">
<constructor-arg type="String" value="信息与计算科学"/>
<constructor-arg type="int" value="08"/>
</bean>
</beans>
package com.fuwh.spring; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Spring01 { public static void main(String[] args) {
/*
* 测试类
*/
//ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"beanStudent.xml","beanClazz.xml"});
//ApplicationContext ac=new ClassPathXmlApplicationContext("beanStudent.xml");
//System.out.println(ac.getBean("student"));
ApplicationContext ac=new ClassPathXmlApplicationContext("beanClazz.xml");
System.out.println(ac.getBean("clazz",Clazz.class));
}
}
基于索引(index)实例:
※需要注意的是,索引是从“0”开始
<?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"> <!-- spring配置文件 -->
<bean id="clazz" class="com.fuwh.spring.Clazz" lazy-init="default">
<constructor-arg index="0" value="信息与计算科学"/>
<constructor-arg index="1" value="08"/>
</bean>
</beans>
基于参数名称(name)实例:
<?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"> <!-- spring配置文件 -->
<bean id="clazz" class="com.fuwh.spring.Clazz" lazy-init="default">
<constructor-arg name="name" value="信息与计算科学"/>
<constructor-arg name="grade" index="1" value="08"/>
</bean>
</beans>
基于setter方法的依赖注入
package com.fuwh.spring; /*
* POJO类
*/
public class Lesson { private String name;
private int score; public void setName(String name) {
System.out.println("name parameter is injected");
this.name = name;
} public void setScore(int score) {
System.out.println("score parameter is injected");
this.score = score;
} @Override
public String toString() {
return "Lesson [name=" + name + ", score=" + score + "学分]";
} }
<?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"> <!-- spring配置文件 -->
<bean id="lesson" class="com.fuwh.spring.Lesson" lazy-init="default"
p:name="php"
p:score="2"/>
</beans>
package com.fuwh.spring; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Spring01 { public static void main(String[] args) {
/*
* 测试类
*/
ApplicationContext ac=new ClassPathXmlApplicationContext("beanLesson.xml");
System.out.println(ac.getBean("lesson",Lesson.class));
}
}
在注入的时候,使用以上两种方式都是可以的,但是在以下一种情况下,只能使用setter的方式注入
Class A的构造方法中需要Class B的实例, Class B的构造方法中又需要Class A的实例,
这时候就会报BeanCurrentlyInCreationException的exception.
级联属性注入
package com.fuwh.test;
public class People {
public int id;
public String name;
public int age;
public Dog dog=new Dog();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", dog=" + dog + "]";
}
}
package com.fuwh.test;
public class Dog {
public int id;
public String name;
public int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "Dog [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
<?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="people" class="com.fuwh.test.People">
<property name="id" value="1"></property>
<property name="name" value="laofu"></property>
<property name="age" value="27"></property> <!-- dog就是属于级联的初始化 -->
<property name="dog.id" value="12"></property>
<property name="dog.name" value="wangcai"></property>
<property name="dog.age" value="11"></property>
</bean> </beans>
最后,使用junit4进行测试
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
People people =(People)ac.getBean("people");
System.out.println(people);
} }
注入集合变量
List
package com.fuwh.test; import java.util.ArrayList;
import java.util.List; public class People { public int id;
public String name;
public int age; public List<String> nameList=new ArrayList<String>(); public List<String> getNameList() {
return nameList;
} public void setNameList(List<String> nameList) {
this.nameList = nameList;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} 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;
} @Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", nameList=" + nameList + "]";
} }
<?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="people" class="com.fuwh.test.People">
<property name="id" value="1"></property>
<property name="name" value="laofu"></property>
<property name="age" value="27"></property> <property name="nameList">
<list>
<value>唱歌</value>
<value>跳舞</value>
<value>编程</value>
</list>
</property>
</bean> </beans>
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
People people =(People)ac.getBean("people"); System.out.println(people);
} }
map
package com.fuwh.test; import java.util.HashMap;
import java.util.Map; public class People { public int id;
public String name;
public int age; public Map<String,String> nameMap=new HashMap<String,String>(); public Map<String, String> getNameMap() {
return nameMap;
} public void setNameMap(Map<String, String> nameMap) {
this.nameMap = nameMap;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} 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;
} @Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", nameMap=" + nameMap + "]";
} }
<?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="people" class="com.fuwh.test.People">
<property name="id" value="1"></property>
<property name="name" value="laofu"></property>
<property name="age" value="27"></property> <property name="nameMap">
<map>
<entry>
<key><value>zhangsan</value></key>
<value>张三</value>
</entry>
<entry>
<key><value>lisi</value></key>
<value>李四</value>
</entry>
</map>
</property>
</bean> </beans>
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
People people =(People)ac.getBean("people"); System.out.println(people);
} }
注入属性
package com.fuwh.test;
import java.util.Properties;
public class People {
private int id;
private String name;
private int age;
private Properties address=new Properties();
public Properties getAddress() {
return address;
}
public void setAddress(Properties address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
}
}
<?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="people" class="com.fuwh.test.People">
<property name="id" value="1"></property>
<property name="name" value="laofu"></property>
<property name="age" value="27"></property> <property name="address">
<props>
<prop key="sheng">shanghai</prop>
<prop key="shi">pudong</prop>
</props>
</property>
</bean> </beans>
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
People people =(People)ac.getBean("people"); System.out.println(people);
} }
bean的自动装配
bean的自动装配总共分为四种方式:
|
no |
(Default) No autowiring. Bean references must be defined via a |
|
byName |
Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named |
|
byType |
Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set. |
|
constructor |
Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is r |
package com.fuwh.test;
public class People {
private int id;
private String name;
private int age;
private Dog dog;
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", dog=" + dog + "]";
}
}
<?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="dog" class="com.fuwh.test.Dog">
<property name="id" value="001"></property>
<property name="name" value="heihu"></property>
<property name="age" value="5"></property>
</bean> <!-- 也可以在beans中定义autowire="byName" 这时候就对所有bean有效-->
<bean id="people" class="com.fuwh.test.People" autowire="byName">
<property name="id" value="1"></property>
<property name="name" value="lisi"></property>
<property name="age" value="27"></property>
</bean> </beans>
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
People people =(People)ac.getBean("people");
System.out.println(people);
}
}
Spring特性--DI的更多相关文章
- Spring+IOC(DI)+AOP概念及优缺点
Spring pring是一个轻量级的DI和AOP容器框架. 说它轻量级有一大部分原因是相对与EJB的(虽然本人从没有接触过EJB的应用),重要的是,Spring是非侵入式的,基于spring开发的应 ...
- myeclipse 去掉spring特性支持
myeclipse10.0 去掉spring支持 手工修改工程目录下的.project文件中相关的内容 删除<nature>com.genuitec.eclipse.springfram ...
- 淘系工程师讲解的使用Spring特性优雅书写业务代码
使用Spring特性优雅书写业务代码 大家在日常业务开发工作中相信多多少少遇到过下面这样的几个场景: 当某一个特定事件或动作发生以后,需要执行很多联动动作,如果串行去执行的话太耗时,如果引入消息中 ...
- spring+IOC+DI+AOP优点分析(一)
Spring是什么: Spring是一个轻量级的DI和AOP容器框架. 说它轻量级有一大部分原因是相对与EJB的(虽然本人从没有接触过EJB的应用),重要的是,Spring是非侵入式的,基于sprin ...
- spring ioc DI 理解
下面是我从网上找来的一些大牛对spring ioc和DI的理解,希望也能让你对Spring ioc和DI的设计思想有更进一步的认识. 一.分享Iteye的开涛对Ioc的精彩讲解 Ioc—Inversi ...
- [置顶] Spring的DI依赖实现分析
DI(依赖注入)是Spring最底层的核心容器要实现的功能之一,利用DI可以实现程序功能的控制反转(控制反转即程序之间之间的依赖关系不再由程序员来负责,而是由Spring容器来负责) 一个简单的例子( ...
- Spring IOC(DI)之注入方式
一次被问到IOC的注入方式,当时脑袋一阵混乱,不知道噻.于是google了一下,发现众说纷纭,有说三种的,有说四种的.都滚犊子吧,还是看看官方文档吧. DI exists in two major v ...
- Spring Ioc DI 原理
IOC(DI):其实这个Spring架构核心的概念没有这么复杂,更不像有些书上描述的那样晦涩.Java程序员都知道:java程序中的每个业务逻辑至少需要两个或以上的对象来协作完成,通常,每个对象在使用 ...
- SSM-Spring-02:Spring的DI初步加俩个实例
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- DI:依赖注入 第一个DEMO:域属性注入 java类:(Car类和Stu类,学生有一辆小汽车) packag ...
随机推荐
- PHP对象在内存堆栈中的分配
对象在PHP里面和整型.浮点型一样,也是一种数据类,都是存储不同类型数据用的, 在运行的时候都要加载到内存中去用,那么对象在内存里面是怎么体现的呢?内存从逻辑上说大体上是分为4段,栈空间段.堆空间段. ...
- 读<<领域驱动设计-软件核心复杂性应对之道>>有感
道可道,非常道. 名可名,非常名. 无名天地之始,有名万物之母. ---老子 关于标题 好久没写东西了,动笔的动机是看完了一本书,想写点总结性的东西,一是为了回顾一下梳理知识点,二是为了日后遗忘时能有 ...
- 快速上手Unity原生Json库
现在新版的Unity(印象中是从5.3开始)已经提供了原生的Json库,以前一直使用LitJson,研究了一下Unity用的JsonUtility工具类的使用,发现使用还挺方便的,所以打算把项目中的J ...
- 消费RabbitMQ时的注意事项,如何禁止大量的消息涌到Consumer
按照官网提供的订阅型写法( Retrieving Messages By Subscription ("push API")) 我发现,RabbitMQ服务器会在短时间内发送大量的 ...
- Spring事物管理
spring事务配置的五种方式 前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只 ...
- 新手!mass 设置问题
mass就是你那个物体的质量啊质量越大,惯性也越大重力也越大.假如你的刚体的mass为1,那么你只要给这个物体9.81N向上的力,你就可以抵消重力,让这个物体悬浮着:但假如这个物体的mass为10,你 ...
- [No00009D]使用visual studio 2015 update3打包程序安装包的简单方法(不需要InstallShield)
注意: 该方法只适用于小型软件的打包发布: 该打包向导可以预先检查需要的运行库支持: 由于visual studio自2012后取消掉了自带的打包程序,如果有需要打包安装,需要使用一个叫用Instal ...
- Hemodynamic response function (HRF) - FAQ
Source: MIT - Mindhive What is the 'canonical' HRF? The very simplest design matrix for a given expe ...
- 《深入理解Java内存模型》读书总结
概要 文章是<深入理解Java内容模型>读书笔记,该书总共包括了3部分的知识. 第1部分,基本概念 包括"并发.同步.主内存.本地内存.重排序.内存屏障.happens befo ...
- 解读ASP.NET 5 & MVC6系列(12):基于Lamda表达式的强类型Routing实现
前面的深入理解Routing章节,我们讲到了在MVC中,除了使用默认的ASP.NET 5的路由注册方式,还可以使用基于Attribute的特性(Route和HttpXXX系列方法)来定义.本章,我们将 ...