用SpringIOC完成helloworld

一、创建maven工程,导入坐标依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

二、编写demo,编写具体的实现方法

package com.qcby.service;

public class Demo {
    public void hello() {
        System.out.println("hello world");
    }
}

三、在resources目录下创建applicationContext.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.xsd">
  	 <!--IOC管理bean-->
    <!--id:类的唯一标识符 class:类的全路径名-->
    <!--    相当于new了名为demo的Demo-->
    <bean id="demo" class="com.qcby.service.Demo" />
</beans>

创建Spring项目没有Spring Config文件怎么办_何妨徐行的博客-CSDN博客

四、编写测试方法

Test包在java测试根下

package com.qcby.Test;

import com.qcby.service.Demo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTest {

    //传统写法
    @Test
    public void run(){
        Demo demo =new Demo();
        demo.hello();
    }
    
//    把创建对象的权利交给spring
    @Test
    public void springdun(){
//        加载配置文件
        ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
//        获取对象
        Demo demo = (Demo) ac.getBean("demo");
        demo.hello();
    }
}

第一种写法是不用springioc的写法,需要我们自己new对象。

第二中我们在applicationContext.xml中<bean id="demo" class="com.qcby.service.Demo" />

相当于new了名为demo的Demo 

接下来该学习如何使用注解和xml了

Spring框架Bean管理-xml_何妨徐行的博客-CSDN博客

Spring框架Bean管理-注解_何妨徐行的博客-CSDN博客

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值