引用Spring官方的一些话:
This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) [1] principle. IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method
大意就是说Spring的IOC也称为DI,对属性内容的注入可以通过属性的setXXX方法进行也可以通过构造方法进行,当然还可以使用工厂模式进行属性内容的注入。
那么什么是DI?什么是IOC呢?
DI:Dependency Injection依赖注入
其实就是一个类中的属性就是依赖
注入呢就是为该属性赋值
比如:
class A{
}
class B{
//依赖
private A a;
//注入
public void setA(A a){
this.a=a;
}
}
那IOC是什么呢?
IOC:Inversion of Control :控制反转
都称为IOC容器,就是为我们创建类的对象并且可以为属性赋值
我们来看看如何使用IOC创建对象:
<?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">
<!--IOC控制反转的对象
可以有多个Bean,一个Bean就是一个反转对象
常用属性:
id/name:bean的唯一标记,不要重复
class:要创建的对象的类全称
scope:对象的创建方式
取值:
1、singleton:单例,在整个ApplicationContext对象中就一个,会维护对象的生命周期
2、protortype:多例,每次调用getBean就新建对象,不会维护对象的生命周期
3、request:将创建的对象存储在HttpServletRequest的setAttribute中
4、session:将创建的对象存储在HttpSession中
5、globalSession:在Prolet环境中,使用,非Prolet中,等价与session
-->
<!--对象属性的值得注入方式 -->
<!--第一种:通过属性的setXXX方法实现注入 -->
<bean id="user" class="cn.code404.pojos.User" scope="singleton">
<!--为属性赋值,借助setXXX -->
<property name="id" value="1"></property>
<property name="userName" value="zhangsan"></property>
<property name="pass" value="123456"></property>
</bean>
</beans>
使用单元测试进行调用:
public class IOCTest {
//IOC使用之前和之后
@Test
public void test1(){
//IOC之前
User user=new User();
System.out.println(user);
//IOC控制
//1、Spring上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//2、获取指定id或name的Bean对象
User user2=(User) context.getBean("user");
System.out.println(user2);
}
}
以上就是Spring的入门使用。