从今天开始逐步学习spring框架,用到的所有jar包都会给大家提供。emmmmmm,大概用三天更新完spring吧,对新手还是很友好的,废话不多说开始今天的课程吧。
一、工程的创建以及jar的引入
今天要讲的spring项目只会用到其中几个核心jar包如下图 红色方框标出的。
现在我们创建工程引入jar包,对了为了方便测试我们这个课程会使用到junit,不会的朋友可以参考我之前的博客。结果如下,别忘记了buildpath
二、创建配置文件 applicationContext
大家一定要看清楚我的配置文件在哪个文件夹下边,下边给出配置文件格式,这里是基本不变的,我不做过多的解释。
<?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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
三、创建实体类,以及测试类
上图中已经给出了位置,下边直接贴代码
User类
package dao;
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
测试类
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.User;
public class TestResult {
@Test
public void fun() {
//创建容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//取user对象
User user = (User) ac.getBean("user");
//打印user
System.out.println(user);
}
}
四、在spring中配置User类
这里要用到bean这个属性,必备的两个基本要求一个是name 一个是class,看代码,回到applicaContext中
<?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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean name="user" class="dao.User"></bean>
</beans>
五、结果测试
右键测试类的fun'函数,junit运行,结果如下
至此第一部分已经结束,都是很基础的操作,代码复制粘贴就应该能跑起来。加油,下一篇博客见。