Spring的3大主要功能:
1. ioc/di
2. aop
3. 声明式事务
一、IOC
ioc:由spring容器去创建实例,不再需要程序员去new实例。
控制:控制类的对象
反转:转交给spring容器去完成
最大作用:解耦(解除了<创建对象和程序员的耦>)
二、Spring环境搭建
- 创建一个web项目
- 导入核心功能的jar包
- 新建applicationContext.xml
(文件名和路径自定义)
applicationContext.xml中配置的信息最终都存储在ApplicationContext容器中。
spring 配置文件基于schema(语法检查器),每次引入xsd时,就是一个xmlns
schema最大的优点就是:扩展性
<?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">
</beans>
——————————————————————————-spring环境搭建完毕————————————————————————
三、例子: 创建对象
- 创建对象
从类路径classes下加载一个xml文件,最后配生成ApplicationContext
package com.company.pojo;
public class People {
private String name;
private int age;
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 [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">
<!-- id表示获取到对象标识
class 创建哪个类的对象
-->
<bean id="peo" class="com.bjsxt.pojo.People"/>
</beans>
/*编写测试类*/
package com.company.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.company.pojo.People;
public class Test {
public static void main (String[] args) {
//没有Spring的写法
// People people = new People();
//使用Spring的IOC功能,需要将People转交给Spring,就得在xml文件中配置<bean id="获取类的标识" calss="全路径名"/>
//配置文件被加载时,实例就被创建
//加载配置文件,形成容器ApplicationContext
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
People people = ac.getBean("peo",People.class);
System.out.println(people);
// String[] names = ac.getBeanDefinitionNames(); //获取容器中的所有pojo
// for (String string : names) {
// System.out.println(string);
// }
}
}