栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring IOC DI 基本操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring IOC DI 基本操作

创建一个名为spring01的Maven Web 项目
并在main包中创建java和resources文件

创建好后在pom.xml中引入依赖
org.springframework spring-webmvc 5.2.0.RELEASE commons-logging commons-logging 1.2
创建dao层和service层

在dao层接口中写入say()方法并在实现类中实现方法

在service层接口中写入say()方法并在实现类中实现方法


在resources中创建applicationContext.xml并在 在applicationContext.xml中注册dao层的bean

创建测试类测试IOC

package com.lijunbo;

import com.lijunbo.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestIoc {
    public static void main(String[] args){
        ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao =context.getBean("userDao",UserDao.class);
    }
}

DI注入
在applicationContext.xml中加入service层的bean并关联dao层bean

 
        
    

创建DI测试类测试DI注入

package com.lijunbo;

import com.lijunbo.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDI {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.say();

    }
}

测试成功

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/755550.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号