在没有 @Autowire 的情况下实例化 Java Spring 存储库接口

Instantiate Java Spring repository interface without @Autowire

这是我的 Spring 存储库界面。

@Repository
public interface WebappRepository extends CrudRepository<myModel, Long> {

}

在我的控制器中,我可以实例化 WebappRepository,即使它是一个接口,因为 Spring 注释魔法。

public class controller{

    @Autowire
    WebappRepository repo;

    public controller(){

    }
}

但是这种使用构造函数的变体 没有 工作,这是正确的,因为 WebappRepository 是一个接口。

public class controller{

    WebappRepository repo;

    public controller(){
        this.repo = new WebappRepository();
    }
}

Olivier Gierke 本人 advocates to avoid @Autowire fields at all costs。如何在我的 Spring 应用程序中 "instantiate" 存储库界面,同时避免 @Autowire?

在构造函数中注入依赖项:

@Component
public class Controller{


    WebappRepository repo;

    @Autowire
    public Controller(WebappRepository repo){
        this.repo = repo;
    }
}

如果您使用的是 Spring 4.3+ 并且您的目标 class 只有一个构造函数,您可以省略自动装配注释。 Spring 将为它注入所有需要的依赖项。 所以写在构造函数下面就足够了:

public controller(WebappRepository repo){
    this.repo = repo;
}

参考:https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation