Spring 一二事(1)

本文介绍了一个简单的Spring入门案例,展示了如何使用Spring 2.5版本创建并管理一个名为HelloWorld的Bean。通过创建配置文件applicationContext.xml,并在其中定义Bean,再通过编写Java类HelloWorld及其测试类HelloWorldTest来实现基本的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单介绍一下spring,一方面带新手入入门,一方面自己也重温一下
第一个小工厂先暂时不用maven,下一个会用maven来来配置

jar包只需要一个,spring版本为2.5(暂时为2.5,后续更新,基本核心都是一样的),引入spring.jar到lib,如下:

在src下新建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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
           
    <!-- 把一个类放入到spring容器中,该类就称为bean -->
    <!-- 描述一个类 id 唯一标示 class 类名 -->
    <bean id="helloWorld" class="com.lee.spring001.createobject.HelloWorld"></bean>

</beans>

在com.lee.spring001.createobject包下新建类HelloWorld.java :

package com.lee.spring001.createobject;

public class HelloWorld {

    public HelloWorld() {
        System.out.println("HelloWorld...");
    }

    /**
     * 
     */
    public void hello() {
        System.out.println("Hello world!");
    }
}

测试:

 1 package com.lee.spring001.createobject;
 2 
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class HelloWorldTest {
 8 
 9     @Test
10     public void testHelloWorld() {
11         
12         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
13         
15         HelloWorld hello = (HelloWorld)context.getBean("helloWorld");
16         hello.hello();
17     }
18 }

这样运行junit,成功

 

github地址:https://github.com/leechenxiang/maven-spring001-helloworld

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值