Educoder Spring入门 第一关:Hello Spring

28 篇文章 9 订阅

创建一个 Spring 项目的基本步骤如下:

1. 引入jar包 → 2. 创建Javabean → 3. 创建Spring的配置文件 → 4. 创建一个主函数入口

        首先,我们需要下载Springjar包 ,为了更好的理解Springjar包依赖,我们不使用maven创建,也不用web.xml文件来初始化加载Spring容器,原始打造。主要目的是为了能观察到一个简单的Spring项目是什么样子。

  • 首先创建lib文件夹,引入jar包,包括4个核心包(beanscorecontextexpression) + 1个依赖(commons-loggins…jar)包:

    4b2fd10bda474e858cd66e40211637f4.png

创建Javabean

创建一个HelloWorld.class

public class HelloWorld {
public HelloWorld(){
System.out.println("初始化构造器");
}
}

创建Spring配置文件,并添加配置对象

  • 位置:任意,开发中一般在classpath(src)

  • 名称:任意,开发中通用applicationContext.xml

因此项目结构如下:

f408f115a908450fa77e6b0882b99b2b.png

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">

<bean id="helloworld" class="educoder.HelloWorld"></bean>
<!-- 注意class 属性值要求为类的全路径 -->

</beans>

创建一个主函数入口

我们需要一个测试类,来检测我们的 Spring 项目是否可用:

public class Test {
public static void main(String[] args) {
//1、创建Spring的IOC容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、从IOC的容器中获取Bean实例
HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloworld");
}
}

然后我们运行程序,若执行完成得到如下结果,说明你的 Spring 项目已经创建成功:

3db580e402724f2286b673ebaf92db74.png

参考答案:

HelloWorld.java

package step1;

public class HelloWorld {
        public void HelloString(){
                System.out.println("Hello Spring");
        }
}

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">
    <bean id="hellost" class="step1.HelloWorld"></bean>
</beans>

Test1.java

package step1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import step1.HelloWorld;
public class Test1 {
	public static void main(String[] args) {
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
                HelloWorld hellost = (HelloWorld)app.getBean("hellost");
                hellost.HelloString();
	}
}

 

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

于建章

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值