Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Spring Constructor Injection

farenda 2016-06-13 0

Spring Constructor Injection

This is one of the simplest and cleanest types of Dependency Injection in the Spring Framework. In this post we show how to use it with help of Spring annotations.

Spring bean to inject as dependency

Let’s specify an interface for dependency:

package com.farenda.spring.tutorial.injection.constructor;

public interface BookRepository {
    String titleById(int id);
}

And the actual Spring Bean implementation that will be injected:

package com.farenda.spring.tutorial.injection.constructor;

import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

@Repository
public class InMemoryBookRepository implements BookRepository {

    // It's our local database ;-)
    private Map<Integer, String> books = new HashMap<>();

    {
        books.put(1, "Effective Java, 2nd edition");
        books.put(2, "Java Concurrency in Practice");
        books.put(3, "Spring in Action");
    }

    @Override
    public String titleById(int id) {
        return books.get(id);
    }
}

Spring component with dependency injected by constructor

Here we define another Spring Bean, but this time we are going to inject BookRepository through constructor, using @Autowired annotation:

package com.farenda.spring.tutorial.injection.constructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Library {

    private BookRepository bookRepository;

    @Autowired
    public Library(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public String findBook(int id) {
        return bookRepository.titleById(id);
    }
}

Spring resolves dependencies using argument’s type. If it finds a bean matching the type, then the bean is instantiated and injected. Else exception is thrown.

Example App using Spring Boot

Here’s the simplest Spring Boot application to run the above code:

package com.farenda.spring.tutorial.injection.constructor;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan // scan this package for Spring beans
public class ConstructorInjection {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication
                .run(ConstructorInjection.class, args);

        // Get bean from the Spring Application Context:
        Library library = context.getBean(Library.class);

        System.out.println("Title 1: " + library.findBook(1));
        System.out.println("Title 2: " + library.findBook(2));
    }
}

The above code produces the following output:

Title 1: Effective Java, 2nd edition
Title 2: Java Concurrency in Practice

References:

  • Check out Spring Boot “Hello, world” if you are new to Spring Boot
Share with the World!
Categories Spring Framework Tags spring, spring-core
Previous: Java Util Map computeIfPresent(Key,BiFunction)
Next: Java Util Map forEach(BiConsumer)

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok