一:spring基本概念

1)struts2是web框架,hibernate是orm框架

2)spring是容器框架,创建bean,维护bean之间的关系

3)spring可以管理web层,持久层,业务层,dao层,spring可以配置各个层的组件,并且维护各个层的关系


二:spring核心原理

1.IOC控制反转

概念:控制权由对象本身转向容器,由容器根据配置文件创建对象实例并实现各个对象的依赖关系。

核心:bean工厂


2.AOP面向切面编程

a.静态代理

根据每个具体类分别编写代理类

根据一个接口编写一个代理类

b.动态代理

针对一个方面编写一个InvocationHandler,然后借用JDK反射包中的Proxy类为各种接口动态生成相应的代理类

三:简单的Spring入门案例

1.编写一个类:UserService

<span style="font-size:18px;">package com.cloud.service;
public class UserService {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void sayHello(){
		System.out.println("hello:"+name);
	}
}</span>

2.编写核心配置文件:applicationContext.xml

<beans xmlns="http://www.springframework/schema/beans"
	xmlns:xsi="http://www.w3/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework/schema/mvc"
	xmlns:context="http://www.springframework/schema/context"
	xmlns:aop="http://www.springframework/schema/aop" xmlns:tx="http://www.springframework/schema/tx"
	xsi:schemaLocation="http://www.springframework/schema/beans 
		http://www.springframework/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework/schema/mvc 
		http://www.springframework/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework/schema/context 
		http://www.springframework/schema/context/spring-context-3.2.xsd 
		http://www.springframework/schema/aop 
		http://www.springframework/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework/schema/tx 
		http://www.springframework/schema/tx/spring-tx-3.2.xsd ">
	<!-- 在容器中配置bean对象 -->
	<!-- 下面这句等价于:UserService userService = new UserService() -->
	<bean id="userService" class="com.cloud.service.UserService">
		<!-- 等价于:userService.setName("SpringName"); -->
		<property name="name">
			<value>SpringName</value>
		</property>
	</bean>
</beans>

3.编写测试类:Test

<span style="font-size:18px;">package com.cloud.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cloud.service.UserService;
public class Test {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) ac.getBean("userService");
		userService.sayHello();
	}
}</span>

四:spring原理总结

1.使用spring ,没有new对象,我们把创建对象的任务交给spring框架
2.spring
实际上是一个容器框架,可以配置各种bean(action/service/domain/dao),并且可以维护beanbean的关系,当我们需要使用某个bean的时候,我们可以getBean(id),使用即可.

更多推荐

Spring框架的基本原理