Spring (1)

Spring 是一个开源的控制反转(IoC Inversion of Control)和面向切片(AOP)面向切面的容器框架,它的做用是简化企业开发。html

请查询关于反转控制的内容。简单来讲:应用自己不负责对象的建立以及维护,对象的建立和维护是由外部容器来负责的,这样控制权就交给了外部容器,减小了代码之间耦合的程度。spring

举一个代码的例子:编程

原先建立一个类:windows

class People{api

  Man xiaoMing = new Man();框架

  public string males;ide

  public int age;测试

}操作系统

咱们实例化一个对象xiaoMing时须要在People类中new一个类,可是经过Spring容器,咱们能够将其交给外部的XML文件来进行实例化,而在People中,咱们仅仅须要声明一个xiaoMing对象便可。code

class Pepele{

  private Man xiaoMing;

  public string males;

  public int age;

}

新建XML配置文件:


 

 

<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd">

......
</beans>

能够直接从Spring的说明文档中复制这样的一段代码。

实例化Spring容器:


 

实例化Spring容器的方法有两种ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.

(1)在类路径下寻找配置文件来实例化容器

ApplicationContext ctx =  new ClassPathXmlApplicationContext(new String[]{"bean.xml"});

(2)在文件系统下寻找配置文件来实例化容器

ApplicationContext ctx =  new FileSystemXmlApplicationContext(new String[]{"d:\\bean.xml"});

因为windows和Linux操做系统的差异,咱们通常使用第一种方式进行实例化。

 

配置bean文件并添加类


 

 

<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="peopleService" name="" class="org.spring.beans.PeopleService">
 </bean>

</beans>

 

public class PeopleService implements PeopleServiceInterf {
 
 /* (non-Javadoc)
  * @see org.spring.beans.PeopleServiceInterf#testBeans()
  */
 @Override
 public void testBeans(){
  System.out.println("测试是否被实例化!");
 }

}

 

测试


 

 

 @Test
 public void test() {
  //实例化Spring容器
  ApplicationContext ctx =  new ClassPathXmlApplicationContext("bean.xml");
  PeopleService peopleService = (PeopleService)ctx.getBean("peopleService");
  peopleService.testBeans();
 }

能够看到测试结果正确,测试输出为 "测试是否被实例化!"

 

优缺点:


 

 

IoC最大的好处是什么?由于把对象生成放在了XML里定义,因此当咱们须要换一个实现子类将会变成很简单(通常这样的对象都是实现于某种接口的),只要修改XML就能够了,这样咱们甚至能够实现对象的热插拔(有点象USB接口和SCSI硬盘了)。另外,Spring容器还提供了AOP技术,能够实现权限拦截,运行期监控等功能;还有就是与Hibernate和JdbcTemplate等第三方框架的整合。
 
IoC最大的缺点是什么?(1)生成一个对象的步骤变复杂了(事实上操做上仍是挺简单的),对于不习惯这种方式的人,会以为有些别扭和不直观。(2)对象生成由于是使用反射编程,在效率上有些损耗。但相对于IoC提升的维护性和灵活性来讲,这点损耗是微不足道的,除非某对象的生成对效率要求特别高。(3)缺乏IDE重构操做的支持,若是在Eclipse要对类更名,那么你还须要去XML文件里手工去改了,这彷佛是全部XML方式的缺憾所在。(百度百科)
相关文章
相关标签/搜索