Spring简单测试(maven)
maven依赖:(建议使用比最新版本稍微低一点的版本,最新版本和你的其他依赖可能产生冲突)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3..3.RELEASE</version>
</dependency>
对,你没看错,只要加这一个依赖就可以了。
spring-context包中的依赖关系包括了spring-aop,spring-beans,spring-core,spring-expression,spring-asm这几个包。所以我们只需要导这一个包就行。
bean类:Student.java
package com.squid.bean;
/**
* @author squid
*
*/
public class Student {
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex
+ ", address=" + location + "]";
}
private String id;//学号
private String name;//姓名
private String sex;//性别
private String location;//家庭住址ַ
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
spring-context.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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="stu" class="com.squid.bean.Student">
<property name="id" value="123"></property>
<property name="name" value="zhangsa"></property>
</bean>
</beans>
测试类:SpringTest.java
package com.squid.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.squid.bean.Student;
public class SpringTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext beanFactory = new ClassPathXmlApplicationContext(
"/conf/spring-context.xml");
Student student = (Student) beanFactory.getBean("stu");
System.out.println(student);
}
}
运行结果:
Student [id=123, name=zhangsa, sex=null, address=null]
测试成功!