实例化 Java Spring 存储库接口,无需@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();
}
}

奥利维尔·吉尔克本人主张不惜一切代价避免@Autowire田。如何在避免@Autowire的同时在 Spring 应用程序中"实例化"存储库接口?

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

@Component
public class Controller{

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

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

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

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

相关内容

最新更新