Spring学习笔记(一)之第一个spring程序

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());

	}
}

注:项目整体结构如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值