一: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) 领域对象

  

 package com.znker.spring.IoC;

 public class Account {

     private long id;
     private String owerName;
     private double balance;

     public long getId() {
         return id;
     }
     public void setId(long id) {
         this.id = id;
     }
     public String getOwerName() {
         return owerName;
     }
     public void setOwerName(String owerName) {
         this.owerName = owerName;
     }
     public double getBalance() {
         return balance;
     }
     public void setBalance(double balance) {
         this.balance = balance;
     }
 }

  2) AccoutDao接口与实现类

package com.znker.spring.IoC;

import java.util.List;

public interface AccountDao {

    public void insert(Account account);

    public void update(Account account);

    /** update方法的重载 */
    public void update(List<Account> accounts);

    public void delete(long accountId);

    public Account find(long accountId);

    public List<Account> find(List<Long> accountIds);

}
package com.znker.spring.IoC;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

@Repository("accountDao")
public class AccountDaoInMemoryImpl implements AccountDao {

    /** HashMap 模拟数据库 */
    private Map<Long, Account> accountsMap = new HashMap<>();

    {
        Account account1 = new Account();
        account1.setId(1L);
        account1.setOwerName("John");
        account1.setBalance(10.0);

        Account account2 = new Account();
        account2.setId(2L);
        account2.setOwerName("Mary");
        account2.setBalance(20.0);

        accountsMap.put(account1.getId(), account1);
        accountsMap.put(account2.getId(), account2);
    }

    @Override
    public void insert(Account account) {
        accountsMap.put(account.getId(), account);
    }

    @Override
    public void update(Account account) {
        accountsMap.put(account.getId(), account);
    }

    @Override
    public void update(List<Account> accounts) {
        for (Account account : accounts) {
            accountsMap.put(account.getId(), account);
        }
    }

    @Override
    public void delete(long accountId) {
        accountsMap.remove(accountId);
    }

    @Override
    public Account find(long accountId) {
        return accountsMap.get(accountId);
    }

    @Override
    public List<Account> find(List<Long> accountIds) {
        List<Account> accounts = new ArrayList<Account>();
        for (Long id : accountIds) {
            accounts.add(accountsMap.get(id));
        }

        return accounts;
    }

}

  3) AccountService接口与实现类

package com.znker.spring.IoC;

public interface AccountService {
    /** 客户之间转账 */
    public void transferMoney(long sourceAccountId, long targetAccountId, double amount);

    /** 客户存款 */
    public void depositMoney(long accountId, double amount);

    public Account getAccount(long accountId);
}
package com.znker.spring.IoC;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transferMoney(long sourceAccountId, long targetAccountId, double amount) {
        Account sourceAccount = accountDao.find(sourceAccountId);
        Account targetAccount = accountDao.find(targetAccountId);
        sourceAccount.setBalance(sourceAccount.getBalance() - amount);
        targetAccount.setBalance(targetAccount.getBalance() + amount);
        /** 更新数据库记录 */
        accountDao.update(sourceAccount);
        accountDao.update(targetAccount);
    }

    @Override
    public void depositMoney(long accountId, double amount) {
        Account account = accountDao.find(accountId);
        account.setBalance(account.getBalance() + amount);
        accountDao.update(account);
    }

    @Override
    public Account getAccount(long accountId) {
        return accountDao.find(accountId);
    }
}

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

    XML文件版:xml-beans.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-3.2.xsd">

    <bean id="accountService" class="com.znker.spring.IoC.AccountServiceImpl">
        <!-- 依赖注入 accountDao -->
        <property name="accountDao" ref="accountDao" />
    </bean>

    <bean id="accountDao" class="com.znker.spring.IoC.AccountDaoInMemoryImpl" />

</beans>

    Java注解版:annotation-beans.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- 扫描类路径中存在的类,通过相关联的注解创建Bean并注入其依赖项中 -->
    <context:component-scan base-package="com.znker.spring.IoC" />

</beans>

  5) 测试类代码

package com.znker.spring.IoC;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
    public static void main(String[] args) {

        /** 基于注解的spring容器对象实例化 */
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfiguration.class);
        /** 基于XML文件的spring容器对象实例化 */
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/znker/spring/IoC/beans.xml");

        // 获取 AccountService Bean
        AccountService accountService = ctx.getBean("accountService", AccountService.class);

        System.out.println("Before money transfer:");
        System.out.println("Account 1 balance : " + accountService.getAccount(1).getBalance());
        System.out.println("Account 2 balance : " + accountService.getAccount(2).getBalance());

        // 转账
        accountService.transferMoney(1, 2, 5.0);

        System.out.println("After money transfer:");
        System.out.println("Account 1 balance : " + accountService.getAccount(1).getBalance());
        System.out.println("Account 2 balance : " + accountService.getAccount(2).getBalance());

    }
}

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. HTML5学习总结

    一.HTML5概念 HTML5并不仅仅只是做为HTML标记语言的一个最新版本,更重要的是它制定了Web应用开发的一系列标准,成为第一个将Web做为应用开发平台的HTML语言. HTML5定义了一系列新 ...

  2. Oracle和SQLServer解锁杀进程

    ORACLE:在平时工作中经常会遇到数据库死锁的情况,以前使用oracle时候(那时候还不懂),出现这种情况时前辈给了我一段命令:SELECT dob.OBJECT_NAME Table_Name,l ...

  3. python基础之迭代与解析

    先简单看一下文件迭代器 >>> f=open('file1') >>> f.readline() "'aaa','bbb','ccc'\n" & ...

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

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

  5. 用PHP向mysql添加数据

    <?php $name=$_POST['name']; $gender = $_POST['gender']; $age=$_POST['age']; #连接到数据库 $link = mysql ...

  6. myeclipse中将整块的代码所选中的代码左右移动的快捷键

    myeclipse中将整块的代码/所选中的代码左右移动的快捷键选择你要移动的代码,TAB 右移ctrl+TAB左移(我的使用Shift+TAB管用)要是不使用快捷键就是:选中代码,点击右键选中Shif ...

  7. .NET获取根目录方法

    1.取得控制台应用程序的根目录方法 方法1.Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径 方法2.AppDomain.CurrentDomain.Ba ...

  8. Java web--Filter过滤器分IP统计访问次数

    分IP统计访问次数即网站统计每个IP地址访问本网站的次数. 分析 因为一个网站可能有多个页面,无论哪个页面被访问,都要统计访问次数,所以使用过滤器最为方便. 因为需要分IP统计,所以可以在过滤器中创建 ...

  9. PHP开发网站之微信登录、绑定

    )))刷新access_token()); ); ); curl_setopt($curlobj, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curlo ...

  10. MarkDown初体验

    初体验 写在前面 一周前第一次听说了MarkDown这个编辑器,通过它知道了LaTex,正好满足了我多年对网上博客里的公式简陋的表达的需求.起初,只是用到了LaTex公式这一个功能 , 对于主要文字的 ...