Eclipse 将此代码视为错误,但它在 Maven 中编译得很好

Eclipse sees this code as error, but it compiles fine in maven

我有一个使用 spring 框架的项目,我正在尝试创建一个 CrudController,Eclipse 指出我的代码有错误,但代码编译正常。

它在 UserController.java::5 -

上失败

Bound mismatch: The type UserService is not a valid substitute for the bounded parameter <S extends Service<M,CrudRepository<M,Long>>> of the type CrudController<M,S>

代码如下:

UserController.java(出现错误的地方)

package app;

import org.springframework.beans.factory.annotation.Autowired;

public class UserController extends CrudController<User, UserService>{

  @Autowired
  @Override
  public void setService(UserService service) {
    this.service = service;
  }

}

CrudController.java

package app;

import org.springframework.data.repository.CrudRepository;
import org.springframework.web.bind.annotation.ResponseBody;

public abstract class CrudController<M extends Model, S extends Service<M, CrudRepository<M,Long>>> {
  S service;
  public abstract void setService(S service);
  public @ResponseBody Iterable<M> getJson() {
    return service.getAll();
  }
}

Model.java

package app;

public class Model {

}

Service.java

package app;

import org.springframework.data.repository.CrudRepository;

public abstract class Service <M extends Model, R extends CrudRepository<M, Long>> {
  R repo;
  public abstract void setRepo(R repo);
  public Iterable<M> getAll() {
    return repo.findAll(); 
  }
}

User.java

package app;

public class User extends Model {

}

UserRepository.java

package app;

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {

}

用户Service.java

package app;

import org.springframework.beans.factory.annotation.Autowired;

public class UserService extends Service<User, UserRepository> {

  @Autowired
  @Override
  public void setRepo(UserRepository repo) {
    this.repo = repo;
  }

}

您的 CrudController 需要 Service 的子类 CrudRepository,

public abstract class CrudController<M extends Model, 
  S extends Service<M, CrudRepository<M,Long>>> { ..

但是你给它一个 Service 的子类和 CrudRepository 的子类。

您可以更改 CrudController 签名 ...

/* takes any CrudRepository */
public abstract class CrudController<M extends Model, 
  S extends Service<M, ? extends CrudRepository<M,Long>>> { ..

/* takes any CrudRepository */
public abstract class CrudController<M extends Model, 
  R extends CrudRepository<M, Long>, S extends Service<M,R>> { ..

/* you'll have to be explicit in UserController with this signature */
public class UserController extends CrudController<User, UserRepository, UserService>{