본문 바로가기

Backend/Java

Spring Beans - Dependency Injection

반응형

In Object Oriented Design, there is a rule called 'SOLID" that is used to increase the reusability and flexibility while decreasing the dependency between programs

  • SRP (Single Responsibility): A class should handle one functionality
  • OCP (Open / Closed Principle): Functions should be expendable but not modifiable
  • LSP (Liskov's Substitution Principle: A child should substitute their parent
  • ISP (Interface Segregation Principle): Interfaces should be separated to handle a small and dedicated function
  • DIP (Dependency Inversion Principle): Class, module, and business logic should depend on abstractions

Today, we will see how we can follow the DIP rule with the dependency injection

List of Contents

Inversion of Control (IoC)

The IoC rule is to outsource the creation and management of objects to the spring container rather than manage them by ourselves. Spring container provides Dependency Injection function to inject the object created

Annotation List

Annotation Injection

▶ @Component

Registers classes as beans. Beans are list of classes managed by Spring. Once registered they can be injected to other classes

@Component

▶ @Primary

Used to set the default bean to be used when there are multiple beans inheriting the same interface. This can only be used for one bean for the same interface

@Primary

Java Code Injection

▶ @Configuration

Allows @Bean annotation to register beans and configuration classes to be used

@Configuration

▶ @Bean

Registers beans to the spring container

@Bean

Common

▶ @Autowired

Used to find the beans registered (either by @Component or @Configuration and @Bean)

@Autowired

▶ @Qualifier

Use to specify a class when multiple classes are inheriting the same interface. This has a priority over the @Primary annotation

@Qualifier("<beanId>")

▶ @Lazy

By default, Spring registers and initializes all the component when start running. This annotation overrides the default and only registers components that are being called

@Lazy


※ We can also use application.properties to use the lazy feature. Note that this will affect every component in the application including the controllers

spring.main.lazy-initialization=true

▶ @SpringBootApplication

Creates application contexts, registers the beans, and runs the Tomcat server. this includes @EnableAutoConfiguration,  @ComponentScan, and @Configuration annotations

@SpringBootApplication

▶ @EnableAutoConfiguration

Activates the auto-configuration

@EnableAutoConfiguration

▶ @ComponentScan

Scans components under the package that this annotation is being used and its sub-packages

@ComponentScan

※ This only scans the annotations registered in the main package that the annotation is used. So packages (e.g., 'other' package shown below) outside the main package are not scanned.

If you call a component in the outside package from the main package, you will see an error

To solve this, add the option shown below to register the component to add to the scan list

@SpringBootApplication(scanBasePackages = "newPackage")
@SpringBootApplication(scanBasePackages = {"newPackage1", "newPackage2"})


Dependency Injection

Dependency injections can be done with XML files, Java source codes, and annotations

Using XML Files

Using XML is not recommended and is not used

Annotation Injection

@Component creates and registers the beans. Constructor injection (used when dependency is mandatory) and setter injection (Adds a dependency automatically when dependencies are not provided) are often used

Annotation Setup

Create an interface

Add an implementation class and add the @Component annotation

Add a controller and add the component as a field

Constructor Injection

Let's see how we can inject dependency using the annotation injection

▶ One Bean

Create a constructor and add @Autowired annotation (Can omit this when there is only one constructor)

▶ Multiple Beans

When there are multiple beans implementing the same interface, Spring throws an error like the one below

To solve this use @Qualifier annotation to specify the bean

Setter Injection

Setter injection uses setters or methods. The process under the hood is as follows

Car car = new BMW();
DemoController demoController = new DemController();
demoController.setCar(car);

Add a setter or a method and tag it with @Autowired

Multiple Beans

Use @Qualifier annotation to specify a bean

Field Injection

In addition, there is a field injection but it is not recommended as it makes unit testing hard

Java Code Injection

Java code injection uses @Configuration and @Bean to create and register beans (when not registered, you will see an error as shown below). Java code injection makes third-party codes can be added as beans to be injected into the application

Create an interface

Create an implementation class

Create a configuration class with @Configuration annotation. Add @Bean annotation to the methods (the method name is the bean ID)


※ We can change the bean name by specifying the ID

@Bean("newBean")
public Car ford() {
  return new Ford();
}

Using the annotation is the same as the annotation injection. Use a constructor or setter

Bean Life Cycles

The post-construct method runs after the constructor is created and the pre-destroy runs when the app stops running

Bean Scopes

singleton

Creates only one bean object when the app runs

@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)

prototype

Creates a bean object each time there is a request to the container. This option does not call the destroy method. So to save the memory, we must destroy the created object by ourselves. Uses @Lazy by default

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

request

Only for HTTP requests and web apps.

session

Only for HTTP requests and web apps.

 

global-session

Only for global HTTP requests and web apps.

 

In this writing, we got to know the dependency injection.


References

SOLID Principle in Programming: Understand With Real Life Examples - GeeksforGeeks

 

SOLID Principle in Programming: Understand With Real Life Examples - GeeksforGeeks

A Computer Science portal for geeks. It contains well-written, well thought, and well-explained computer science and programming articles, quizzes, and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

728x90
반응형

'Backend > Java' 카테고리의 다른 글

Switch  (0) 2023.12.26
Spring Boot Form  (10) 2023.10.28
Spring Boot Security  (1) 2023.10.01
Spring Boot Actuator  (0) 2023.10.01
Data Persistency Tools (JPA, Hybernate, Mybatis)  (3) 2023.09.09