本教程适合刚入门spring的同学,讲一下spring的简单使用
首先创建一个maven工程,导入spring的jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
创建一个实体类User
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
创建Dao接口以及简单实现
UserDao接口,有一个添加方法和通过id获取user方法
public interface UserDao {
void addUser(User user);
User getUser(Integer id);
}
接口的简单实现,我们的目的是使用spring,所以就不直接调用数据库了
public class UserDaoImpl implements UserDao {
private final List<User> user = new ArrayList<>();
@Override
public void addUser(User user) {
this.user.add(user);
System.out.println("添加成功");
}
@Override
public User getUser(Integer id) {
List<User> collect = user.stream().filter(w -> w.getId().equals(id)).collect(Collectors.toList());
if (collect.size() <= 0) {
return null;
}
return collect.get(0);
}
}
创建service接口以及实现类
接口中也定义了两个方法,添加和获取user
public interface UserService {
void addUser(User user);
User getUser(Integer id);
}
实现类中我们需要通过set方法,把UserDao进行注入
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
@Override
public User getUser(Integer id) {
return userDao.getUser(id);
}
}
接下来我们就可以进行测试了,看我们的bean交给spring之后是否可以创建成功
public class UserServiceTest {
private UserService userService;
@Before
public void getBean() {
// 通过类路径读取解析xml文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
userService = (UserService) applicationContext.getBean("userService");
}
@Test
public void addUser() {
User user = new User();
user.setId(1);
user.setUsername("tom");
user.setPassword("123456");
userService.addUser(user);
System.out.println(userService.getUser(1));
}
}
我们调用一下测试方法,可以看到我们的程序正常运行