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

了解spring框架构造具体流程

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

了解spring框架构造具体流程

实现步骤: 工程大概结构:
1.新建maven项目

 

 

 修改仓库

 按图设置

2.加入依赖,修改pom.xml
spring-context : spring依赖junit:

pom.xml


        
        
            org.springframework
            spring-context
            5.2.5.RELEASE
        

        
        
            junit
            junit
            4.12
            test
        
    
3.开发人员定义类:接口和实现类类也可以没有接口。
接口和实现类定义:和没有spring一样。

DemoService接口

package com.fzf.service;

public interface DemoService {
    public void sayHello();
}
package com.fzf.service.impl;

import com.fzf.service.DemoService;



public class DemoServiceImpl implements DemoService {
    @Override
    public void sayHello() {
        System.out.println("hello");
    }
}
4.创建spring的配置文件。作用:声明对象。把对象交给spring创建和管理。
使用表示对象声明,一个bean表示一个java对象。

beans.xml





    
    


5.使用容器中的对象。
创建一个表示spring容器的对象 Applicationcontext从容器中,根据名称获取对象,使用getBean("对象名称")

DemoMain

package com.fzf;

import com.fzf.service.DemoService;
import com.fzf.service.impl.DemoServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;



public class DemoMain {
    public static void main(String[] args) {
        //未使用spring管理对象前
        //DemoService demoService=new DemoServiceImpl();
        //demoService.sayHello();

        //使用spring管理
        //1.指定spring配置文件:从类路径(classspath)之下开始的路径
        String config="beans.xml";
        //2.创建容器对象,ApplicationContext表示spring容器对象。通过ctx获取java对象
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);

        //3.从容器中获取指定名称的对象,使用getBean("id")
        DemoService demoService = (DemoService) ctx.getBean("demoService");

        //4.调用对象的方法,接口中的方法
        demoService.sayHello();
    }
}

MyTest:测试类

package com.fzf;

import com.fzf.service.DemoService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.swing.*;



public class MyTest {

    @Test
    public void test01(){
        String config="beans.xml";
        ApplicationContext ctx =new ClassPathXmlApplicationContext(config);
        DemoService service = ctx.getBean(DemoService.class);
        service.sayHello();
    }
}

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

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

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