Try using DI container with Laravel and Spring Boot

Introduction

This is an article from Your Meister Advent Calendar 2019 Day 13. (This is an article that outputs what you have learned since you became a member of society.)

Background of this time

After becoming a member of society, I learned the concept of DI (Dependency Injection). When developing web services, there were many occasions when I used a framework, but I remember that the concept of DI did not appear in the Cake PHP that I mainly used. (I'm sorry if I have a wrong memory.)

DI uses a pre-registered instance by using what is called a DI container or service container (called a DI container in Spring Boot and a service container in Laravel) instead of creating an instance with new and using it. To do.

This time, I would like to write an article on the theme of using DI containers in Spring Boot, which I use for business, and using service containers in Laravel, which I am learning by myself recently.

For Spring Boot

Use constructor injection

I will write using the code I wrote in the article on the 7th day of Your Meister Advent Calendar 2019. Try to switch DB dynamically with Spring Boot https://github.com/Masaki-Ogawa/datasourceDemo

  1. PersonRepository.java

PersonRepository.java


package com.example.dataSourceDemo.domain.repositories;

import com.example.dataSourceDemo.domain.models.Person;
import org.springframework.data.jpa.repository.JpaRepository;

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {

}

Repository class that inherits JpaRepository

  1. PersonServiceImpl.java

PersonServiceImpl.java


package com.example.dataSourceDemo.domain.services;

import com.example.dataSourceDemo.annotations.DataSource;
import com.example.dataSourceDemo.annotations.DataSource.DataSourceType;
import com.example.dataSourceDemo.domain.models.Person;
import com.example.dataSourceDemo.domain.repositories.PersonRepository;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {

  private final PersonRepository personRepository;

  public PersonServiceImpl(
      PersonRepository personRepository) {
    this.personRepository = personRepository;
  }

  /**
   *Method to get Person table record from stg DB
   * @record in the return Person table
   */
  @Override
  public List<Person> findAllPersonInStg() {
    return personRepository.findAll();
  }

  /**
   *Method to get Person table record from stg DB
   * @record in the return Person table
   */
  @DataSource(value = DataSourceType.PROD)
  @Override
  public List<Person> findAllPersonInProd() {
    return personRepository.findAll();
  }
}

I am doing DI here.

In particular,


private final PersonRepository personRepository;

  public PersonServiceImpl(
      PersonRepository personRepository) {
    this.personRepository = personRepository;
  }

DI is performed by constructor injection in the part of. It is registered in the DI container by using the annotations @ Service and @ Repository. To use it, create an instance using constructor injection etc. as described above.

reference Spring Framework Summary-About DI

DI in Laravel

Use a service provider

Create a service provider to register the created service as a service container. This time, I created a service class called DemoService.

AppServiceProvider.php


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Services\DemoService');
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Register the service as described above.

DemoService.php


class DemoService {
    public function show() {
        echo "Show something";
    }
}

The service class is suitable this time, but only implement the method that outputs some characters.

DemoController.php


class MessageController extends Controller
{
    protected $demoService;

    public function __construct(DemoService $demoService)
    {
        $this->demoService = $demoService;
    }

    public function index(Request $request) {

        return $this->demoService->show();
    }
}

In this way, we also use constructor injection to do DI.

At the end

Personally, I feel that Spring Boot, which can be registered in the DI container with annotations such as @ Service and @ Controller, is easier to use. After all, using Java and Spring Boot, there are many situations where the power of annotation is noticed.

Also, as I wrote in the Advent calendar on the 7th day, each framework has good and bad points, and the experience of touching many frameworks is that when I make something in the future, "What kind of thing should I adopt?" If so, is it the best for the product? "

In the future, I would like to continue to touch on both business and non-business.

Recommended Posts

Try using DI container with Laravel and Spring Boot
Try using Spring Boot with VS Code
Try using Spring Boot Security
Try using OpenID Connect with Keycloak (Spring Boot application)
Part 1: Try using OAuth 2.0 Login supported by Spring Security 5 with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Asynchronous processing with Spring Boot using @Async
Image Spring Boot app using jib-maven-plugin and start it with Docker
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP
Try to implement login function with Spring Boot
Try to automate migration with Spring Boot Flyway
Try using another Servlet container Jetty with Docker
Try DI with Micronaut
First Spring Boot (DI)
Download with Spring Boot
Try using Spring JDBC
Create a portfolio app using Java and Spring Boot
Testing JPA entities and repositories using Spring Boot @DataJpaTest
[Note] Configuration file when using Logback with Spring Boot
Switch environment with Spring Boot application.properties and @Profile annotation
Spring Security usage memo: Cooperation with Spring MVC and Boot
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
Spring Boot with Spring Security Filter settings and addictive points
Try Dependency Inversion Principle with Multiple Spring Boot Projects
Test field-injected class in Spring boot test without using Spring container
Attempt to SSR Vue.js with Spring Boot and GraalJS
Try to work with Keycloak using Spring Security SAML (Spring 5)
Connect Spring Boot and Angular type-safely with OpenAPI Generator
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Try using GloVe with Deeplearning4j
Try using view_component with rails
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Using Mapper with Java (Spring)
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Try Spring Boot on Mac
Create microservices with Spring Boot
Send email with spring boot
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
Try hitting the zip code search API with Spring Boot
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
Connect to database with spring boot + spring jpa and CRUD operation
Implement REST API with Spring Boot and JPA (domain layer)
Domain Driven Development with Java and Spring Boot ~ Layers and Modules ~
I tried to get started with Swagger using Spring Boot