Spring有两大核心,其一是控制反转/依赖注入(ioc),本文将仔细介绍该知识点的实际应用,从而凸显其特点。
一、介绍
ioc是一种设计思想,并非技术。使用该设计思想意味着对象的创建将从传统 对象内部转为由Spring容器
直接控制(整个生命周期),所以从这这种角度来看,控制权发生转变了,因此可以用控制反转来形容;同
时对象也有容器直接注入给需要调用的对象,所以从这种角度看称为依赖注入。
传统设计:
ioc设计:
IOC/DI优缺点
优点:①将对象的创建交给容器,提高开发效率
缺点:①对象的创建时通过反射来实现的,因此会有一定的效率损耗。
二 实例
1 创建java project
2 下载jar包
Spring集成包下载地址:https://repo.spring.io/release/org/springframework/spring
3 实体类 User.java
package com.spring;
public class User {
private Integer id;
private String name;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
4 applicationContext.xml(src根目录下)
<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-3.0.xsd">
<!---spring创建bean->
<bean class="com.spring.User">
<!--通过set给name属性注入值-->
<property name="name" value="石义宾"/>
</bean>
</beans>
5 测试类
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//加载并初始化配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean(对象)
User user = (User)applicationContext.getBean(User.class);
System.out.println(user.getName());
}
}
6 项目结构