spring项目搭建
一、创建maven项目
二、添加依赖
添加spring-context依赖和junit4依赖(方便后面测试)。
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 自定义spring的版本-->
<spring.version>5.3.13</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
spring-context包含了core、aop、beans、expression,所以只需要引入context依赖即可。
三、创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
四、创建User类
创建User类和set、get、有参和无参构造方法。
package entity;
public class User {
private int id;
private String code;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, String code, String name) {
this.id = id;
this.code = code;
this.name = name;
}
public User() {
}
@Override
public String toString() {
return "user{" +
"id=" + id +
", code='" + code + '\'' +
", name='" + name + '\'' +
'}';
}
}
五、配置bean
<?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">
<!--id:名字任意,一般为类名的小写,class:类的全限定名 -->
<bean id="user" class="entity.User">
<property name="id" value="1"></property>
<property name="code" value="0001"></property>
<property name="name" value="张三"></property>
</bean>
</beans>
六、打印输出
package entity;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
User user = (User)context.getBean("user");
System.out.println(user);
}
}