1.Spring
概念:Spring是一个基于IOC和AOP的结构J2EE系统的框架。
Ioc(反转控制Inversion Of Control):简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象。
2.DI(依赖注入 Dependency Inject):简单地说就是拿到的对象的属性,已经被注入好相关值了,直接使用即可。//我这里用applicationContext.xml
演示案例:
- pojo
public class Category {
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;
}
private int id;
private String name;
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + "]";
}
}
3.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><bean name="c" class="com.how2java.pojo.Category">
<property name="id" value="007" />
<property name="name" value="mababa" />
</bean>
3.Test package com.how2java.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.how2java.pojo.Category;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" }); //实用的Bean工厂ApplicationContext
//Category d = new Category(); new创建对象
Category c = (Category) context.getBean("c"); //ioc
System.out.println(c.getName());
System.out.println(c.toString());
}
}
原理图:
以获取对象的方式来进行比较
传统的方式:
通过new 关键字主动创建一个对象
IOC方式:
对象的生命周期由Spring来管理,直接从Spring那里去获取一个对象。 IOC是反转控制 (Inversion Of Control)的缩写,就像控制权从本来在自己手里,交给了Spring。
打个比喻:
传统方式:相当于你自己去菜市场new 了一只鸡,不过是生鸡,要自己拔毛,去内脏,再上花椒,酱油,烤制,经过各种工序之后,才可以食用。
用 IOC:相当于去馆子(Spring)点了一只鸡,交到你手上的时候,已经五味俱全,你就只管吃就行了。
图解
Spring 官方文档对 bean 的解释是:
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
在 Spring 中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。bean是一个由Spring IoC容器实例化、组装和管理的对象。
bean规范如下:
1.所有属性为private
2.提供默认构造方法
3.提供getter和setter
实现serializable接口