Magnus
Magnus

Reputation: 728

Instantiate Java Spring repository interface without @Autowire

This is my Spring repository interface.

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

}

In my controller, I can instantiate the WebappRepository even though it's an interface, because of Spring annotation magic.

public class controller{

    @Autowire
    WebappRepository repo;

    public controller(){

    }
}

But this variant, using the constructor, does not work, and rightly so, because WebappRepository is an interface.

public class controller{

    WebappRepository repo;

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

Olivier Gierke himself advocates to avoid @Autowire fields at all costs. How can I "instantiate" the repository interface in my Spring application while avoiding the @Autowire?

Upvotes: 0

Views: 6177

Answers (2)

xingbin
xingbin

Reputation: 28279

Inject dependencies in constructor:

@Component
public class Controller{


    WebappRepository repo;

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

Upvotes: 3

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

If you're on Spring 4.3+ and your target class has just one constructor, you can omit autowired annotation. Spring will inject all the needed dependencies for it. So writing just below constructor would suffice:

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

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

Upvotes: 2

Related Questions