1,Spring 概述
- spring 是一个开源框架
- spring 是一个IOC和AOP容器框架
- spring 的特性:非侵入式,依赖注入,面向切面编程,容器,组件化,一站式。
2, IOC和DI
IOC(Inversion of Control):反转控制
在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效率。
反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。
DI(Dependency Injection):依赖注入
IOC的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。
IOC 描述的是一种思想,而DI 是对IOC思想的具体实现.
IOC容器在Spring中的实现
1)在通过IOC容器读取Bean的实例之前,需要先将IOC容器本身实例化。
2)Spring提供了IOC容器的两种实现方式
① BeanFactory:IOC容器的基本实现,是Spring内部的基础设施,是面向Spring本身的,不是提供给开发人员使用的。
② ApplicationContext:BeanFactory的子接口,提供了更多高级特性。面向Spring的使用者,几乎所有场合都使用ApplicationContext而不是底层的BeanFactory
3,实现helloworld
一个简单的spring项目需有三个文件:
- 创建对象的类
- 配置文件 ApplicationContext.xml
- main类
1,Address.class 用来创建对象,提供get,set方法:
package com.spring.relation;
public class Address {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
}
2, 创建spring Bean Configuration file
ApplicationContext.xml :
<?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 = "address1" class = "com.spring.relation.Address">
<property name="city" value = "BeiJing"></property>
<property name="street" value = "wudaokou"></property>
</bean>
</bean>
3,创建main函数:
package com.spring.hellowold;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class main_test {
public static void main(String[] args) {
//获取person对象
//1,创建Spring的IOC容器对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//2,获取address对象
Address add1 = ctx.getBean("address1",Address.class);
System.out.println(add1)
}
}
来源:CSDN
作者:酷酷的丁
链接:https://blog.csdn.net/lijiaxingli8/article/details/104113917