你的位置:首页 > 软件开发 > Java > Spring 学习笔记01

Spring 学习笔记01

发布时间:2017-09-01 00:00:12
1.Spring 简介 Spring 是为企业提供的一个轻量级的解决方案,包括:基于依赖注入的核心机制,基于AOP的声明式事务管理,与多种持久层技术的集合以及优秀的WEB MVC框架等。Spring 框架的组成结构: ...

Spring 学习笔记01

1.Spring 简介

      Spring 是为企业提供的一个轻量级的解决方案,包括:基于依赖注入的核心机制,基于AOP的声明式事务管理,

与多种持久层技术的集合以及优秀的WEB MVC框架等。

Spring 框架的组成结构:

       Spring 学习笔记01

 

2.Spring 准备工作

      1)首先在官网下载Spring 压缩文件并解压

      2)将jar包导入eclipse的项目中

           Spring 学习笔记01

3.Spring 的使用

   Spring 核心容器就是一个超级大工厂,所有的对象都被当成Spring核心容器管理的对象,称为Bean。

   首先定义两个类 Pen 和 Person:

public class Pen {  public String write(){  return "用笔写字"; } }
public class Person {  private Pen pen;  public void setPen(Pen pen){  this.pen = pen; }  public void usePen(){  System.out.println("我要写字");  System.out.println(pen.write()); }}

Person中userPen()方法中用到了Pen的write()方法,也就是Person依赖于Pen,Sring就是处理这些Bean的对象之间的依赖和对象的创建的。

因此在src目录下面创建applicationContext.

 

<??><beans ="http://www.springframework.org/schema/beans" ="http://www.w3.org/2001/ ="http://www.springframework.org/schema/context" ="http://www.springframework.org/schema/util"  ="http://www.springframework.org/schema/aop" ="http://www.springframework.org/schema/tx" ="http://www.springframework.org/schema/data/jpa" ="http://www.springframework.org/schema/mvc" xsi:schemaLocation="           >>    <bean id="person" class="com.huan.example.Person">  <property name="pen" ref="pen"></property> </bean> <bean id="pen" class="com.huan.example.Pen"></bean></beans>

   Spring会根据配置文件的bean通过反射机制调用该类的无参构造创建对象,并以id作为key值放入到Sring容器中,称为Spring中的Bean 。

Person中的<property>子元素,Spring会利用反射执行Person中的setter方法,也就是setPen()方法,将ref指向的pen这个Bean作为参数注入到

Person中。

    新建一个类进行测试:

public class TestPerson { public static void main(String[] args) {  //加载配置文件,创建Spring容器  ApplicationContext ac = new ClassPath);  //根据id获取相应的Bean对象,不需要new  Person p = ac.getBean("person", Person.class);  //调用对象的方法  p.usePen(); }}

ApplicationContext 接口主要有实现类:ClassPath

在类加载路径下搜索配置文件,后者是在文件系统的相对路径或绝对路径下搜索配置文件。

运行测试类结果:

Spring 学习笔记01

从上面可以看出使用了Spring框架之后不再使用new调用构造器创建对象,所有的java对象都由Spring容器负责创建。

原标题:Spring 学习笔记01

关键词:Spring

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录