欢迎进群交流(QQ群:655019021)
一、Spring入门程序
第一步:下载Spring
开发环境:STS3.9 + Spring5.*
开发工具:STS全称Spring Tool Suite,基于Eclipse定制的Srping应用程序工具
也可以选择Eclipse安装sts插件或使用Idea
下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/
目前最新稳定版本5.0.6:
docs:文档
libs:jar包
schema:约束文件
*.txt说明文档
第二步:新建项目导入jar包
第三步:新建包和相关类
UserService.java
新建测试类:
UserTest.java
这样的方式显然不是我们要的,并没有体现出来Spring的任何价值。
第四步:新建Spring配置文件
在src路径下编写配置文件
创建方式一:
File —> new--> other,输入Spring搜索,选择Spring Bean Configuration File
文件名没有要求,一般为ApplicationContext.xml
此方式创建以后会自动导入Spring相关的约束头文件。
方式二:
创建一个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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
第五步:修改测试类
修改UserTest.java
package com.itcodeschool.demo;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclass UserTest {
@SuppressWarnings("resource")
publicstaticvoid main(String[] args) {
//直接new对象方式调用servcie方法
/* UserService service = new UserService();
service.service();*/
//使用Spring框架方式调用service方法
//指定spring核心配置文件,加载Spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//指定类型从容器中获取对象
UserService userService = applicationContext.getBean(UserService.class);
//调用对象的service方法
userService.service();
}
}