spring2.5的第一个简单应用的学习

Spring 是一个开源的控制反转(Inversion of Control,IoC) 和面向切面(AOP)的容器框架,

容器提供的声明式事物


实例化Spring容器常用的两种方式:
方法一:
在类路径下寻找配置文件来实例化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});//数组是因为可以指定多个配置文件可根据不同模块配置


方法二:
在文件系统路径下寻找配置文件来实例化容器
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String []{"d:\\beans.xml"})

所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护又外部容器创建,这样控制权就有应用转移到了外部容器,控制权的转移就是反转
如何把对象交个spring容器管理

建立一个业务Bean

import cn.itcast.service.impl;


public class PersonServiceBean {
         public  void Save(){
             System.out.printl("我是Save");
     }   //要实现软件的解耦 实现接口
}

简单学习一下如何创建接口 抽取接口
右击-->Refactor-->Extract Interface-->输入接口的名称-->对方法打钩-->点击OK
如此上面的业务Bean类就变成

import cn.itcast.service.impl;


public class PersonServiceBean implements PersonService{
         public  void Save(){
             System.out.printl("我是Save");
     }   //要实现软件的解耦 实现接口
}


/***这是接口***/

package cn.itcast.service.impl;


public interface PersonService {
 
       public void save();
}


在beans.xml文件中做配置
模板可以去拷贝

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">  id属性是为bean起名称 并且是唯一 通过ID获取到这个Bean不可以使用特殊字符如:"/ss"  name属性同样是为Bean起名 可以使用特殊字符"/"

</bean> 顾名思义 class指定的就是我们要交个Spring管理Bean类 Bean配置好后这个时候Bean类就会由Spring帮我们创建和维护
编写spring配置文件时,不能出现帮助信息

由于spring的schema文件位于网路上,如果机器不能连接到网络,那么在编写
配置信息时候就无法出现提示信息,解决方法有两种:

1.让机器上网,eclipse会自动从网络上下载schema文件并缓存在硬盘上
2.手动添加schema文件,方法如下:
windown->preferences->myeclipse->files and editors->xml->xmlcatalog点"add",
在出现的窗口中的Key Type中选择URL,
在location中选“File System”,
然后再spring解压目录的dist/resources目录中选择spring-beans-2.5.xsd,回到设置窗口的时候不要急着关闭窗口,
应把窗口中的Key TYpe改为Schema location, Key改为http://www.springframework.org/schema/beans/spring-beans-2.5.xsd


ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService=(PersonService)ctx.getBean("personService");//用这个方法从容器中获取刚才我们交个Spring的容器
/***当获取到Bean的名称时我们可以通过Bean的接口对它进行引用***/
这样就可以调用业务类的方法
personService.save();

总结: 在beans.xml文件中我们指定的业务Bean类也就是实现

实例化容器后直接从容器中取得这个Bean然后再调用业务Bean的方法Save();

/**********************/
循环所有Bean对象
for(String beanName : sigletons.keySet())
{
          //获取Bean对象、
          判断是否存在
          存在获取属性
          for()循环属性描述
          取得setter方法 properdesc.getWriteMethod();
          seeter方法是否存在注解  采用反射技术判断是否存在注解、
          存在的话
          判断是否有属性名取得resource注解
          如果指定了该属性的name值
          取得Bean对象 根据注解的name属性把Bean从spring容器中取出来 把引用对象注入到属性
          如果没有为注解的name属性赋值
          那么就取得属性的名称
          for循环所有实体然后
          判断属性的类型和Bean是否相匹配
          使用方法isAssignableFrom()
          取得Bean的Class
          //把引用对象注入到属性
}
/**********************/

原文地址:https://www.cnblogs.com/wuhuisheng/p/2108242.html