一:Spring中重要的概念

  1. 容器( container ) : spring容器( ApplicationContext )的工作原则是创建容器中的组件( instance ),处理组件之间的依赖关系,并将这些组件装配到一起。

  2. 控制反转( Inversion of Controll ) : 组件的依赖项由容器在运行时注入( injection ),而非组件自己实例化( new ),对依赖项的控制由组件转移到了容器。

二:依赖注入( dependency injection)

  1. Bean的定义:应用程序中由Spring容器进行管理的对象称为Bean

  2. IoC容器负责application中对象的实例化、初始化、装配和生命周期的管理。

三:IoC-demo

  1. 新建Java项目,添加工程Jar包

    1) spring核心包:org.springframework.beans、org.springframework.core、org.springframework.context

    2) Java日志包:commons.logging、org.apcha.log4j 和 Log4j.properties 配置文件

  2. demo代码

    1) 领域对象

  

  1. package com.znker.spring.IoC;
  2.  
  3. public class Account {
  4.  
  5. private long id;
  6. private String owerName;
  7. private double balance;
  8.  
  9. public long getId() {
  10. return id;
  11. }
  12. public void setId(long id) {
  13. this.id = id;
  14. }
  15. public String getOwerName() {
  16. return owerName;
  17. }
  18. public void setOwerName(String owerName) {
  19. this.owerName = owerName;
  20. }
  21. public double getBalance() {
  22. return balance;
  23. }
  24. public void setBalance(double balance) {
  25. this.balance = balance;
  26. }
  27. }

  2) AccoutDao接口与实现类

  1. package com.znker.spring.IoC;
  2.  
  3. import java.util.List;
  4.  
  5. public interface AccountDao {
  6.  
  7. public void insert(Account account);
  8.  
  9. public void update(Account account);
  10.  
  11. /** update方法的重载 */
  12. public void update(List<Account> accounts);
  13.  
  14. public void delete(long accountId);
  15.  
  16. public Account find(long accountId);
  17.  
  18. public List<Account> find(List<Long> accountIds);
  19.  
  20. }
  1. package com.znker.spring.IoC;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7.  
  8. import org.springframework.stereotype.Repository;
  9.  
  10. @Repository("accountDao")
  11. public class AccountDaoInMemoryImpl implements AccountDao {
  12.  
  13. /** HashMap 模拟数据库 */
  14. private Map<Long, Account> accountsMap = new HashMap<>();
  15.  
  16. {
  17. Account account1 = new Account();
  18. account1.setId(1L);
  19. account1.setOwerName("John");
  20. account1.setBalance(10.0);
  21.  
  22. Account account2 = new Account();
  23. account2.setId(2L);
  24. account2.setOwerName("Mary");
  25. account2.setBalance(20.0);
  26.  
  27. accountsMap.put(account1.getId(), account1);
  28. accountsMap.put(account2.getId(), account2);
  29. }
  30.  
  31. @Override
  32. public void insert(Account account) {
  33. accountsMap.put(account.getId(), account);
  34. }
  35.  
  36. @Override
  37. public void update(Account account) {
  38. accountsMap.put(account.getId(), account);
  39. }
  40.  
  41. @Override
  42. public void update(List<Account> accounts) {
  43. for (Account account : accounts) {
  44. accountsMap.put(account.getId(), account);
  45. }
  46. }
  47.  
  48. @Override
  49. public void delete(long accountId) {
  50. accountsMap.remove(accountId);
  51. }
  52.  
  53. @Override
  54. public Account find(long accountId) {
  55. return accountsMap.get(accountId);
  56. }
  57.  
  58. @Override
  59. public List<Account> find(List<Long> accountIds) {
  60. List<Account> accounts = new ArrayList<Account>();
  61. for (Long id : accountIds) {
  62. accounts.add(accountsMap.get(id));
  63. }
  64.  
  65. return accounts;
  66. }
  67.  
  68. }

  3) AccountService接口与实现类

  1. package com.znker.spring.IoC;
  2.  
  3. public interface AccountService {
  4. /** 客户之间转账 */
  5. public void transferMoney(long sourceAccountId, long targetAccountId, double amount);
  6.  
  7. /** 客户存款 */
  8. public void depositMoney(long accountId, double amount);
  9.  
  10. public Account getAccount(long accountId);
  11. }
  1. package com.znker.spring.IoC;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5.  
  6. @Service("accountService")
  7. public class AccountServiceImpl implements AccountService {
  8.  
  9. @Autowired
  10. private AccountDao accountDao;
  11.  
  12. public void setAccountDao(AccountDao accountDao) {
  13. this.accountDao = accountDao;
  14. }
  15.  
  16. @Override
  17. public void transferMoney(long sourceAccountId, long targetAccountId, double amount) {
  18. Account sourceAccount = accountDao.find(sourceAccountId);
  19. Account targetAccount = accountDao.find(targetAccountId);
  20. sourceAccount.setBalance(sourceAccount.getBalance() - amount);
  21. targetAccount.setBalance(targetAccount.getBalance() + amount);
  22. /** 更新数据库记录 */
  23. accountDao.update(sourceAccount);
  24. accountDao.update(targetAccount);
  25. }
  26.  
  27. @Override
  28. public void depositMoney(long accountId, double amount) {
  29. Account account = accountDao.find(accountId);
  30. account.setBalance(account.getBalance() + amount);
  31. accountDao.update(account);
  32. }
  33.  
  34. @Override
  35. public Account getAccount(long accountId) {
  36. return accountDao.find(accountId);
  37. }
  38. }

  4) 为spring 容器提供Bean实例化和装配所需的配置元数据(congfiguration metadata),配置元数据可以用XML文件或Java注解提供。

    XML文件版:xml-beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
  6.  
  7. <bean id="accountService" class="com.znker.spring.IoC.AccountServiceImpl">
  8. <!-- 依赖注入 accountDao -->
  9. <property name="accountDao" ref="accountDao" />
  10. </bean>
  11.  
  12. <bean id="accountDao" class="com.znker.spring.IoC.AccountDaoInMemoryImpl" />
  13.  
  14. </beans>

    Java注解版:annotation-beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  9.  
  10. <!-- 扫描类路径中存在的类,通过相关联的注解创建Bean并注入其依赖项中 -->
  11. <context:component-scan base-package="com.znker.spring.IoC" />
  12.  
  13. </beans>

  5) 测试类代码

  1. package com.znker.spring.IoC;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6.  
  7. public class TestMain {
  8. public static void main(String[] args) {
  9.  
  10. /** 基于注解的spring容器对象实例化 */
  11. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfiguration.class);
  12. /** 基于XML文件的spring容器对象实例化 */
  13. ApplicationContext ctx = new ClassPathXmlApplicationContext("com/znker/spring/IoC/beans.xml");
  14.  
  15. // 获取 AccountService Bean
  16. AccountService accountService = ctx.getBean("accountService", AccountService.class);
  17.  
  18. System.out.println("Before money transfer:");
  19. System.out.println("Account 1 balance : " + accountService.getAccount(1).getBalance());
  20. System.out.println("Account 2 balance : " + accountService.getAccount(2).getBalance());
  21.  
  22. // 转账
  23. accountService.transferMoney(1, 2, 5.0);
  24.  
  25. System.out.println("After money transfer:");
  26. System.out.println("Account 1 balance : " + accountService.getAccount(1).getBalance());
  27. System.out.println("Account 2 balance : " + accountService.getAccount(2).getBalance());
  28.  
  29. }
  30. }

Spring Framework 笔记(一):IoC的更多相关文章

  1. Spring学习笔记1——IOC: 尽量使用注解以及java代码(转)

    在实战中学习Spring,本系列的最终目的是完成一个实现用户注册登录功能的项目. 预想的基本流程如下: 1.用户网站注册,填写用户名.密码.email.手机号信息,后台存入数据库后返回ok.(学习IO ...

  2. Spring学习笔记1——IOC: 尽量使用注解以及java代码

    在实战中学习Spring,本系列的最终目的是完成一个实现用户注册登录功能的项目. 预想的基本流程如下: 1.用户网站注册,填写用户名.密码.email.手机号信息,后台存入数据库后返回ok.(学习IO ...

  3. spring学习笔记之---IOC和DI

    IOC和DI (一)IOC (1) 概念 IOC (Inverse of Control) 反转控制,就是将原本在程序中手动创建对象的控制权,交给spring框架管理.简单的说,就是创建对象控制权被反 ...

  4. Spring学习笔记2——表单数据验证、文件上传

    在上一章节Spring学习笔记1——IOC: 尽量使用注解以及java代码中,已经搭建了项目的整体框架,介绍了IOC以及mybatis.第二节主要介绍SpringMVC中的表单数据验证以及文件上传. ...

  5. Spring Framework 学习笔记——核心技术之Spring IOC

    Spring Framework 官网文档学习笔记--核心技术之Spring IOC 官方文档 spring-framework-5.3.9 1. Spring Framework 核心技术 1.1 ...

  6. Hello Spring Framework——依赖注入(DI)与控制翻转(IoC)

    又到年关了,还有几天就是春节.趁最后还有些时间,复习一下Spring的官方文档. 写在前面的话: Spring是我首次开始尝试通过官方文档来学习的框架(以前学习Struts和Hibernate都大多是 ...

  7. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->使用spring framework的IoC容器功能----->方法一:使用XML文件定义beans之间的依赖注入关系

    XML-based configuration metadata(使用XML文件定义beans之间的依赖注入关系) 第一部分 编程思路概述 step1,在XML文件中定义各个bean之间的依赖关系. ...

  8. 框架应用:Spring framework (一) - IoC技术

    IoC概念以及目标 IoC就是让原本你自己管理的对象交由容器来进行管理,其主要的目的是松耦合. IoC发展史 既然IoC的目标是为了松耦合,那它怎么做到的? 最后目标:降低对象之间的耦合度,IoC技术 ...

  9. Spring笔记:IOC基础

    Spring笔记:IOC基础 引入IOC 在Java基础中,我们往往使用常见关键字来完成服务对象的创建.举个例子我们有很多U盘,有金士顿的(KingstonUSBDisk)的.闪迪的(SanUSBDi ...

随机推荐

  1. 施耐德Sepam 40系列备自投逻辑

    1# 主供: VL1= NOT PVTS_1_3 V1 = VL1 AND P59_1_7 AND P59_1_8 AND P59_1_9VL2 = VL1 AND I12 AND I21 AND I ...

  2. iOS平台使用陀螺仪传感器

    在移动端开发过程中,有时候会用到陀螺仪传感器获取当前手机的姿态,下面给出iOS端如何获取陀螺仪姿态数据的代码: //根据陀螺仪的四元数转换为矩阵 + (GLKMatrix4)calculateMatr ...

  3. spring3 项目更新

    列志华 (组长) http://www.cnblogs.com/liezhihua/ 团队guihub https://github.com/LWHTF/OrderingFood 黄柏堂 http:/ ...

  4. hibernate的环境配置

    1,首先把跟Hibernate相关的jar包导入到lib目录下: 2,写Javabean类 package chen.can.Dao; public class TRegister implement ...

  5. <读书笔记>软件调试之道 :问题的核心-诊断

    声明:本文档的内容主要来源于书籍<软件调试修炼之道>作者Paul Butcher,属于读书笔记. 不要急于动手! 尽管可以利用各种工具和技术以及软件自身查找缺陷,但是你最重要的财富是你的智 ...

  6. 让window.close不提示:您查看的网页正在试图关闭窗口。是否关闭此窗口?

    正常来说,当我们调用window.close来关闭从地址栏中打开的窗口时,IE会弹出提示说:您查看的网页正在试图关闭窗口,是否关闭此窗口? 你可以将window.close替换成下边的脚本,然后再测试 ...

  7. Python: 列表的基本用法

    列表是可变的,可以改变的序列,它能够保存任何数据类型. >>> list = []        #定义一个空列表>>> list.append(1)        ...

  8. Entity Framework技术导游系列 开篇 (转)

    在微软平台写程序有年头了,随着微软数据存取技术的持续演化,我在程序中先后使用过ODBC.DAO.ADO.ADO.NET.LINQ to SQL. Entity Framework这些技术. 近几年来, ...

  9. kafka生产消息的速度跟什么有关?

    kafka的吞吐量很大,在保证带宽的情况下,网上的一些测试表明3台broker,没有replication,6个partition的情况下,一般的写入速度可以达到300MB/s.参考:kakfa测试 ...

  10. [Altera]PLL仿真

    EDA Tools: 1.Quartus II 13.1(64-bit) 2.Modelsim SE-64 10.1c Time: 2016.05.05 ----------------------- ...