[JAVA] Introduction to Spring Boot ① ~ DI ~

In advancing the learning of Spring, I will summarize the information I searched for in the teaching materials and online. I'm almost inexperienced in frameworks, so it's super introductory.

Before you start

First of all, what is "Spring Boot"? The scale of "Spring Framework" has become huge, and it has become difficult to understand how to use it. That's where "Spring Boot" came in.

--No need for complicated XML configuration files --Includes web container such as Tomcat

It is a framework that makes it possible to quickly create and execute Spring-based applications by taking advantage of such features. Please understand that it is an easy application creation using "Spring Framework".

Now, let's acquire the knowledge necessary to create a Spring application one by one.

DI(Dependency Injection)

DI is "dependency injection" in Japanese. In terms of meaning, it should be understood as "injecting an object". By injecting dependencies (objects) from outside the class, it has the purpose of resolving the dependencies between classes.

DI container

It is a framework to realize DI. Create and manage instances via DI containers. In addition to resolving class dependencies, you can also get the following side effects:

-The scope of the instance can be controlled. → Whether to generate it every time or to make it a singleton, etc. -Event control is possible for the life cycle of the instance. → Event processing at the time of generation and destruction, etc. -Common processing can be embedded. -Because the objects are loosely coupled, it is easier to test.

Bean definition

Defines a configuration file for the DI container to manage the instance. There are three setting methods.

This time we will look at the settings in annotation.

Annotation

Bean definition is done by adding annotation to JAVA source. Important annotations

@Component @ComponentScan @Autowired

Will be.

ComponentScan

It is an annotation that registers the class with Component annotation in the DI container. Same package as the class with ComponentScan annotation Scans the following classes and registers them in the DI container.

SpringSampleApplication.java


//@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class SpringSampleApplication {

	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(SpringSampleApplication.class, args);
		SampleB sampleb = context.getBean(SampleB.class);
		sampleb.testDi();
	}
}

@SpringBootApplication is running @Configuration, @EnableAutoConfiguration, @ComponentScan. In the sample code, annotations are intentionally added separately.

Component

Attach it to the class to inject. If you add the Component annotation to a class, the DI container will manage the class for you.

SampleA.java


@Component
public class SampleA {
		
	public String getClassName() {
		return this.getClass().getName();
	}
}

A component that only returns its own class name.

Autowired

Attach to the field to be injected. The DI container looks for matching objects and injects them into the fields annotated with Autowired.

SampleB.java


@Component
public class SampleB {

	@Autowired
	private SampleA sampleA;
	
	public void testDi() {
		System.out.println("called " + sampleA.getClassName());
	}
}

Have the sampleA instance injected from the DI container. Now you can get the class name of sampleA.

Since SampleB also needs to be called by the main method, it is registered as a component.

important point

The following cases do not seem to be DI.

・ Static DI -DI in the newly generated instance

This time, because it is executed by the main method

SpringSampleApplication.java


@Autowired
private static SampleB sampleb;
/*abridgement*/
sampleb.testDi();

Loose

SpringSampleApplication.java


SampleB sampleb = new SampleB();
sampleb.testDi();

I tried, but both did not DI well and I got a NullPointerException.

Remarks

In addition to Component, there are some annotations that can be scanned. Let's use each annotation properly according to the role of the class.

@Controller(@RestController) → Target MVC Controller @Service → Targeting service layers such as business logic @Repository → Target classes that perform DB access such as DAO

Reference material

[First Spring Boot](https://www.amazon.co.jp/%E3%81%AF%E3%81%98%E3%82%81%E3%81%A6%E3%81%AESpring- Boot% E2% 80% 95% E3% 80% 8CSpring-Framework% E3% 80% 8D% E3% 81% A7% E7% B0% A1% E5% 8D% 98Java% E3% 82% A2% E3% 83% 97% E3% 83% AA% E9% 96% 8B% E7% 99% BA-I% E3% 83% BB-BOOKS / dp / 4777518655) Reintroduction to spring-DI (Dependency Injection) DI / DI container, do you understand properly ...?

Recommended Posts

Introduction to Spring Boot ① ~ DI ~
Introduction to Spring Boot ② ~ AOP ~
Introduction to Spring Boot Part 1
[Introduction to Spring Boot] Form validation check
First Spring Boot (DI)
An introduction to Spring Boot + in-memory data grid
[Introduction to Spring Boot] Authentication function with Spring Security
Introduction to Ratpack (7) --Guice & Spring
[Introduction to Spring Boot] Submit a form using thymeleaf
How to use ModelMapper (Spring boot)
Upgrade spring boot from 1.5 series to 2.0 series
Introduction to Ruby 2
Introduction to Spring Boot x OpenAPI ~ OpenAPI made with Generation gap pattern ~
Spring Fox ① Introduction
Introduction to SWING
Challenge Spring Boot
Story when moving from Spring Boot 1.5 to 2.1
Introduction to web3j
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
Introduction to Micronaut 1 ~ Introduction ~
[Java] Introduction to Java
Introduction to migration
Changes when migrating from Spring Boot 2.0 to Spring Boot 2.2
Spring Boot Form
Introduction to java
Spring Boot Memorandum
gae + spring boot
Introduction to Doma
DI SessionScope Bean in Spring Boot 2 Filter
How to split Spring Boot message file
[Java] Spring DI ③
Add spring boot and gradle to eclipse
Introduction to Java development environment & Spring Boot application created with VS Code
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
How to make Spring Boot Docker Image smaller
The story of raising Spring Boot 1.5 series to 2.1 series
Try to implement login function with Spring Boot
Major changes related to Spring Framework 5.0 DI container
How to add a classpath in Spring Boot
How to bind to property file in Spring Boot
Try to automate migration with Spring Boot Flyway
[Java] Article to add validation with Spring Boot 2.3.1.
I wanted to gradle spring boot with multi-project
Apply Twitter Bootstrap 4 to Spring Boot 2 using Webjars
[Spring Boot] How to refer to the property file
Spring Boot --How to set session timeout time
SPRING BOOT learning record 01
Introduction to JAR files
Spring Boot + Heroku Postgres
Introduction to Ratpack (8)-Session
Spring Framework Summary-About DI
Introduction to RSpec 1. Test, RSpec
Spring boot memo writing (1)
Introduction to bit operation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
SPRING BOOT learning record 02
Spring Boot2 cheat sheet
Introduction to PlayFramework 2.7 ① Overview
Spring Boot exception handling