第一个Spring程序
本篇文章说说Spring的第一个程序,上篇说了Spring的jar文件
配合视频教程观看,更易理解吸收,动力节点老杜的Spring6教程采用难度逐步递进的方式,从入门的第一个程序到手写Spring框架,真正的能够让小白成为老手。如果你是老程序员不妨看看手写Spring框架,也会让你受益颇多。
相关的学习资料也给大家备好了
前期准备:
- 打开IDEA创建Empty Project:spring6
编辑
- 设置JDK版本17,编译器版本17
编辑
- 设置IDEA的Maven:关联自己的maven
编辑
- 在空的工程spring6中创建第一个模块:spring6-001-first
编辑
第一步:添加spring context的依赖,pom.xml配置如下
<project xmlns="maven.apache.org/POM/4.0.0"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xsi:schemaLocation="maven.apache.org/POM/4.0.0 maven.apache.org/xsd/maven-4…
4.0.0
com.powernode
spring6-001-first
1.0-SNAPSHOT
jar
repository.spring.milestone
Spring Milestone Repository
org.springframework
spring-context
6.0.0-M2
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
注意:打包方式jar。
当加入spring context的依赖之后,会关联引入其他依赖:
spring aop:面向切面编程
spring beans:IoC核心
spring core:spring的核心工具包
spring jcl:spring的日志包
spring expression:spring表达式
编辑
第二步:添加junit依赖
<project xmlns="maven.apache.org/POM/4.0.0"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xsi:schemaLocation="maven.apache.org/POM/4.0.0 maven.apache.org/xsd/maven-4…
4.0.0
com.powernode
spring6-001-first
1.0-SNAPSHOT
jar
repository.spring.milestone
Spring Milestone Repository
org.springframework
spring-context
6.0.0-M2
junit
junit
4.13.2
test
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
第三步:定义bean:User
package com.powernode.spring6.bean;
/**
* bean,封装用户信息。
* @author 动力节点
* @version 1.0
* @since 1.0
*/
public class User {
}
第四步:编写spring的配置文件:beans.xml。该文件放在类的根路径下。
编辑
上图是使用IDEA工具自带的spring配置文件的模板进行创建。
配置文件中进行bean的配置。
<beans xmlns="www.springframework.org/schema/bean…"
xmlns:xsi="www.w3.org/2001/XMLSch…"
xsi:schemaLocation="www.springframework.org/schema/bean… www.springframework.org/schema/bean…
bean的id和class属性:
- id属性:代表对象的唯一标识。可以看做一个人的身份证号。
- class属性:用来指定要创建的java对象的类名,这个类名必须是全限定类名(带包名)。
第五步:编写测试程序
package com.powernode.spring6.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Spring6Test {
@Test
public void testFirst(){
// 初始化Spring容器上下文(解析beans.xml文件,创建所有的bean对象)
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// 根据id获取bean对象
Object userBean = applicationContext.getBean("userBean");
System.out.println(userBean);
}
}
第七步:运行测试程序
编辑