Spring是什么 《Srping in action》阅读笔记

大四,自从十月十三号拿到offer之后就没有看过书,没有敲过代码了,颓废了两个月的心终于有点虚了。于是,决定叫亲爱的豆子来监督我看书,哈哈哈。博文是我的阅读笔记,主要是记录一下书中重要的知识点,以便以后复习用。

转入正题,话说昨天去UC面试实习生,又被问到了spring的作用是什么。以我的大四面试经历来说,面试官都特喜欢问这个问题,《Spring in action》这本书总结的很好。

 

Spring是一个轻量级的DI和AOP容器框架:

1.轻量级:从大小和应用开支上说都是轻量级的。Spring是非侵入式的;基于Spring开发的应用中的对象一般不依赖于Spring类。

2.依赖注入:一种松耦合技术,对象是被动接受依赖类而不是自己主动去找。也可以这样理解:对象不是从容器中查找它的依赖类,而是容器在实例化对象的时候主动将它的依赖类注入给它。

3.面向切面:通过将业务逻辑从应用服务(如监控和事务管理)中分离出来,实现了内聚开发。

4.容器:Spring是一个容器,因为它包含并且管理应用对象的生命周期和配置。

5.框架:Spring实现了使用简单的组件配置组合成一个很复杂的应用。在Srping中,应用中的对象是通过XML文件配置组合起来的。并且提供了很多的基础功能(事务管理,持久层集成等),这使开发人员能够专注于开   发应用逻辑。

 

一个简单的Spring例子,用依赖注入来输出举世闻名的hello world。

 

GreetingService 接口将实现从接口中分离

public interface GreetingService {
void sayGreeting();
}

 

GreetingServiceImpl 打印举世闻名的hello world

public class GreetingServiceImpl implements GreetingService {
private String greeting;
public GreetingServiceImpl(){}
//当用构造器注入(<constructor-arg value="xxx"/>)时需要用到此构造方法
public GreetingServiceImpl(String greeting) {
this.greeting = greeting;
}

public void sayGreeting() {
System.out.println(greeting);
}
//setter方法注入时容器调用此方法
public void setGreeting(String greeting) {
this.greeting = greeting;
}

}

 

在Spring中配置hello world

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

<bean id="greetingService" class="com.rason.chapter01.hello.GreetingServiceImpl">

//setter注入
<property name="greeting" value="hello world!"></property>

//构造器注入

<constructor-arg value="hello world">

</bean>

</beans>

 

测试类

public class GreetingTest {


public static void main(String[] args) {
// 此处用到的BeanFactory就是Spring容器
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
"applicationContext.xml"));
GreetingService greetingService = (GreetingService) factory
.getBean("greetingService");
greetingService.sayGreeting();
}

}

 

以上是一个非常简单的DI例子,只是简单地注入一个字符串属性,Spring的强大之处在于如何使用DI将一个bean注入到另一个bean中。



posted @ 2011-12-14 17:40  rason2008  阅读(361)  评论(1编辑  收藏  举报