レイヤード デカップリング - IOC&DI - はじめに

IOC&DI の概要

分離操作を実現するには、引き続き 3 層アーキテクチャのケースを使用します。特定の記事については、「記事の作成 - CSDN Creation Center」を参照してください。

ステップ

  • Servic層とDao層の実装クラスはIOCコンテナに引き継がれる
  • コントローラーとサービスのランタイム依存オブジェクトを挿入する
  • テストを実行する 

@Componentを使用すると、現在のクラスが IOC 管理 (IOC コンテナ内の Bean と呼ばれます) に引き渡されることを意味します。

@Autowired を使用して、IOC コンテナがこのタイプの Bean オブジェクトを提供し、それを変数に割り当てて依存関係の注入を完了することを示します。 

具体的なキーコードは以下の通りです

package com.example.Service.impl;

import com.example.DAO.EmpDao;
import com.example.DAO.impl.EmpDaoA;
import com.example.POJO.Emp;
import com.example.Service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component     // TODO 将当前类交给IOC容器管理,称为IOC容器中的bean
public class EmpServiceA implements EmpService {
    @Autowired // TODO 运行时,IOC容器会提供该类型的bean对象,并赋值给该变量 即依赖注入
    private EmpDao empDao;

    @Override
    public List<Emp> listEmp() {
        // 调用dao获取数据
        List<Emp> empList = empDao.listEmp();
        empList.stream().forEach(emp -> {
            // 处理gender: 1:男;2:女
            String gender = emp.getGender();
            if ("1".equals(gender)) {
                emp.setGender("男");
            } else if ("2".equals(gender)) {
                emp.setGender("女");
            }
            // 处理job:1:讲师;2:班主任;3:就业辅导
            String job = emp.getJob();
            if ("1".equals(job)) {
                emp.setJob("讲师");

            } else if ("2".equals(job)) {
                emp.setJob("班主任");
            } else if ("3".equals(job)) {
                emp.setJob("就业辅导");
            }
        });
        return empList;
    }
}

おすすめ

転載: blog.csdn.net/weixin_64939936/article/details/131707210