1.Spring介绍
Spring 是一个开源框架,Spring可以做很多事情,它为企业级开发提供这些功能的底层都依赖于它的两个核心特性:IOC和AOP。
- IOC:所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。
- AOP:为 Aspect Oriented Programming 的缩写,意为:面向切面编程,可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术
1.2 spring优点
(1)方便解耦,简化开发(高内聚,低耦合)
- Spring就是一个容器,可以将所有对象创建和依赖关系维护,都交给spring管理
- spring工厂用于生成bean
(2)AOP编程的支持
- 可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术
(3)声明式事务的支持
- 只需要通过配置就可以完成对事务的管理,无需手动编程
(4)方便程序的测试
- spring对Junit4支持,可以通过注解方便的测试spring程序
(5)方便集成各种优秀框架
- spring内部提供了对各种优秀框架的支持,如mybatis等
(6)降低javaEE API的使用难度
- spring对javaEE开发中非常难用的一些api(jdbc等)提供了封装,使这些API使用难度降低
2.第一个spring程序
step1:导入jar包
step2:创建两个javabean类teacher和student,student类的属性依赖于teacher类
public class Teacher {
String name;
int age;
public class Student
{
String name;
int age;
Teacher tea;
step3:创建spring配置文件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-3.0.xsd">
<bean id="teacher" class="com.pojo.Teacher">
<property name="name" value="Zhangsan"></property>
<property name="age" value="25"></property>
</bean>
<bean id="stu" class="com.pojo.Student">
<property name="name" value="lisi"></property>
<property name="age" value="22"></property>
<property name="tea" ref="teacher"></property>
</bean>
</beans>
step4:编写测试类,使用spring容器
public class Main {
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext(new String[] {"ApplicationContext.xml"});
Student stu=(Student)context.getBean("stu");
System.out.println(stu.getName()+"\t"+stu.getAge()+"/t"+stu.getTea());
}
}
注:项目整体结构如下