Search code examples
spring

Why use spring beans instead of object initialization


I am trying to understand the idea of spring beans and why I should use them. If I create a bean and use it to print something out like this.

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Account acc = (Account)context.getBean("account");
acc.printAccName();

Why not just create an object of that class like this

Account acc2 = new Account();
acc.printAccName();

I have been watching some video's and did some reading but I did not get an answer why it is better.


Solution

  • Usually what you inject is business logic or services which typically is what changes in a system.

    You are trying to inject a domain object Account these objects are not subject to change so it is okay to create the object via new. Perhaps, this is what it is confusing you.

    The idea, is to let the container handle the instantiation of your logic or services that change regularly so you can swap them easily without having to open the client classes, because these might be already in production, tested and a developer could potentially introduce new bugs and break things. One way to avoid this is to follow a principle called Open-Closed principle. Then you code to abstractions so you can easily inject concrete implementations via dependency injection.

    Imagine the following scenario. For a bookstore, you have different implementations of how to save a book into a database e.g. using JDBC BookServiceJDBCImpl, or using an ORM BookServiceHibernateImpl etc..

        // Create & get the Spring container, where you configure your implementations
        // e.g. bookServiceJDBC, or bookServiceHibernate
        ApplicationContext container = new ClassPathXmlApplicationContext("spring-config.xml");
    
        // the container loads the appropriate bean say bookServiceHibernate
        BookService bookService = (BookService) container.getBean("bookService");
    
        //Create a new book this is a domain object usually you use new
        Book newBook = new Book("1234", "Spring in Action","Rod Johnson");
        //Now save the book using the implementation defined in the 
        //container 
        bookService.registerNewBook(newBook);
    

    This is how part of the container file may look like, in here you define the concrete implementation:

    <bean id="bookService" class="service.BookServiceHibernateImpl"/>
    

    By letting the container handle this you could inject different implementations without having to touch the client class or even knowing which implementation will be passed.

    Check this Dependency Injection blog post it explains a way to achieve it using Spring.

    Bear in mind that in Spring you can use java annotations or xml, and that there are different ways to inject dependencies e.g. via get/set, constructors etc this is just an illustrative example of the general DI concept. The design is up to the developer.