创建一个 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();
	}
}

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐