spring基本原理概念
阿新 • • 發佈:2019-01-09
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;
- publicclass UserService {
- private String name;
- public String getName() {
- return name;
- }
- publicvoid setName(String name) {
- this.name = name;
- }
-
public
- System.out.println("hello:"+name);
- }
- }</span>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"
-
xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
- <!-- 在容器中配置bean物件 -->
- <!-- 下面這句等價於:UserService userService = new UserService() -->
- <beanid="userService"class="com.cloud.service.UserService">
- <!-- 等價於:userService.setName("SpringName"); -->
- <propertyname="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;
- publicclass Test {
- publicstaticvoid 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),並且可以維護bean與bean的關係,當我們需要使用某個bean的時候,我們可以getBean(id),使用即可.