Spring Boot アプリ作成

Spring Bootで簡単なアプリを作成

[2.1.1]

/hajiboot-di/src/main/java/com/example/hajibootdi/Calculator.java

package com.example.hajibootdi;

public interface Calculator {
    int calc(int a, int b);
}

/hajiboot-di/src/main/java/com/example/hajibootdi/AppConfig.java

package com.example.hajibootdi;
import com.example.hajibootdi.AddCalculator;
import com.example.hajibootdi.Calculator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class AppConfig {
    @Bean
    Calculator calculator() {
        return new AddCalculator();
    }
}

/hajiboot-di/src/main/java/com/example/hajibootdi/AddCalculator.java

package com.example.hajibootdi;

//import com.example.hajibootdi.HajibootDiApplication.Calculator;


public class AddCalculator implements Calculator {
    @Override
    public int calc(int a, int b) {
        return a + b;
    }
}   

/hajiboot-di/src/main/java/com/example/hajibootdi/HajibootDiApplication.java

package com.example.hajibootdi;
import com.example.hajibootdi.Calculator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;

import java.util.Scanner;
@EnableAutoConfiguration
@Import(AppConfig.class)
public class HajibootDiApplication {
    public static void main (String[] args) {
        ApplicationContext context = SpringApplication.run(HajibootDiApplication.class, args);
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter 2 numbers like 'a b' : ");
        
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        
        Calculator calculator = context.getBean(Calculator.class);
        int result = calculator.calc(a, b);
        
        System.out.println("result = " + result);
    }
}

実行

Enter numbers like 'a b';

#100 200
result = 300