Spring (1)

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

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

举一个代码的例子:

原先创建一个类:

class People{

  Man xiaoMing = new Man();

  public string males;

  public int age;

}

我们实例化一个对象xiaoMing时需要在People类中new一个类,但是通过Spring容器,我们可以将其交给外部的XML文件来进行实例化,而在People中,我们仅仅需要声明一个xiaoMing对象即可。

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方式的缺憾所在。(百度百科)
原文地址:https://www.cnblogs.com/CBDoctor/p/4145706.html