对Spring基础的学习

spring基础:

在本部分,将介绍spring框架的两个核心特性:反向控制(Ioc)和面向切面编程(AOP)。

a. 首先,简单介绍springIocAOP

b. 其次,装配Bean,介绍如何利用Ioc实现系统对象间的松耦合关联,如何使用XMLspring容器中定义系统对象,装配其依赖的类。

c. 创建切面,介绍springAOP把系统服务(如安全和监控)从被服务对象中解耦出来。

Spring简介

Spring特点:

Spring是一个轻量级的IocAOP容器架构。

轻量级:从大小及系统开支上说。且spring是非侵入式的(基于spring开发的系统中对象一般不依赖于spring的类)

反向控制:使用IOC对象时被动接受依赖类而不是主动去找(容器在实例化对象时主动将其依赖类注入给它)

面向切面:将业务逻辑从系统服务中分离实现内聚开发。系统对象制作其该做的业务逻辑不负责其它的系统问题(如日志和事务支持)

容器:包含且管理系统对象的生命周期和配置,通过配置设定bean是单一实例还是每次请求产生一个实例,并设定bean之间的关联关系

框架:使用简单组件配置组合成一个复杂的系统,系统的对象时通过xml文件配置组合起来的,且spring提供了很多基础功能(事务管理、持久层集成等)

Spring模块

Spring框架由7个模块组成:

² 核心容器:提供了基础功能。包含BeanFactory类(spring框架的核心,采用工厂模式实现IOC

² 应用上下文模块:扩展了BeanFactory,添加了对I18N(国际化)、系统生命周期事件及验证的支持,并提供许多企业级服务,并支持与模板框架的集成。

² AOP模块:对面向切面提供了丰富的支持,是spring应用系统开发切面的基础;并引入metadata编程

² JDBCDAO模块

² OR映射模块

² WEB模块:建立在应用上下文模块的基础上,提供了适合web系统的上下文,另外,该模块支持多面向web的任务,入透明处理多文件上传请求,自动将请求参数绑定到业务对象中等。

² MVC框架:

所有模块都是建立在核心容器之上的,容器规定如何创建、配置和管理bean,以及其他细节

Spring的简单示例:

GreetingService将实现从接口中分离出来:

public interface GreetingService {

public void sayGreeting();

}

GreetingServiceImpl负责输出:

public class GreetingServiceImpl implements GreetingService {

private String greeting;

public void sayGreeting() {

// TODO Auto-generated method stub

System.out.println(greeting);

}

public void setGreeting(String greeting) {

this.greeting = greeting;

}

public GreetingServiceImpl() {

}

}

Spring配置xml文件

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="greetingService" class="cn.csdn.service.GreetingServiceImpl">

<property name="greeting" value="Hello">

</property>

</bean>

</beans>

测试类:

package cn.csdn.junit;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.csdn.service.GreetingServiceImpl;

public class GreetingTest {

@Test

public void test(){

//解析xml文件

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");

GreetingServiceImpl gsi=(GreetingServiceImpl) ac.getBean("greetingService");

gsi.sayGreeting();

}

}

<!--EndFragment-->

猜你喜欢

转载自wangyujie.iteye.com/blog/1051207
今日推荐