-2

Maybe the best way to give a question will be to show code below :

public class DBConnection {


    private String Host;
    private String username;
    private String password;

    public DBConnection(String Host, String username, String password)
    {
        this.Host = Host;
        this.username = username;
        this.password = password;
    }

    public void addUser(String name)
    {
        System.out.println("add to db");
    }
}

And class below :

public class UserService {

    public DBConnection dbConnection;

    public UserService(DBConnection dbConnection){

        this.dbConnection = dbConnection;
    }

    public void register()
    {
        dbConnection.addUser("xd");
    }

}

And now, why i have to use spring for DI ? I can't see difference between above code and code below (of course in below case i know that in DBConnection i have to use @Component):

public class UserService {

    public DBConnection dbConnection;

    @Autowired
    public UserService(DBConnection dbConnection){

        this.dbConnection = dbConnection;
    }

    public void register()
    {
        dbConnection.addUser("xd");
    }

}

I can do DI without Spring. What is advantage of using spring Boot?

  • The difference is in picking up a book/googling/watching a tutorial - marking down for no research effort – J Asgarov May 10 '21 at 07:08

2 Answers2

0

Single constructor is concidered as @Autowired by Spring. Then there is no difference.

If there are multiple constructors, then you must mark one of them as @Autowired to let Spring know which ctor should be used to instantiate the bean.

Vladimir Shefer
  • 661
  • 3
  • 19
0

Traditionally, Spring always needed @Autowired (or the newer @Inject) to tell it where to supply dependencies. As of Spring 4.3 (several years ago), if there is exactly one constructor on a class, the Spring container will understand that of course it has to use that constructor and will call it with the necessary dependencies. @Autowired is still needed if you have more than one constructor.

You can certainly do DI without a container, and one of the advantages of using constructor injection is that unit testing is simpler because you can inject mock dependencies. However, in actual applications the number of dependencies gets very large, and an advantage of a DI container is that it handles the bookkeeping for you. Spring also provides a number of other features, including Web APIs (MVC or WebFlux), AOP services (transactions, retry, tracing), convenient data access (Spring Data projects), automatic configuration (Boot), and more.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152