public interface UserMapper {
void insertUser(User user);
User findUserById(int id);
}
现在我们有一个实现了`UserMapper`接口的类`UserMapperImpl`:
public class UserMapperImpl implements UserMapper {
public void insertUser(User user) {
// 实现插入用户到数据库的逻辑
}
public User findUserById(int id) {
// 实现根据ID查找用户的逻辑
return new User(); // 假设返回一个用户实例
}
}
如果我们想要在另一个类中使用`UserMapper`,我们可以这样做:
import com.google.inject.Inject;
public class UserService {
private UserMapper userMapper;
@Inject
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public void addUser(User user) {
userMapper.insertUser(user);
}
public User getUser(int id) {
return userMapper.findUserById(id);
}
}