스프링 프레임워크의 다양한 기능을 코드와 함께 설명하겠습니다. 여기서는 간단한 예제들을 통해 스프링의 핵심 개념인 DI(Dependency Injection), 스프링 부트 애플리케이션, 스프링 MVC 컨트롤러를 살펴보겠습니다.
1. Dependency Injection (DI)
스프링에서 DI는 구성파일(XML) 또는 자바 기반의 설정파일(@Configuration)을 통해 이루어질 수 있습니다. 여기서는 가장 일반적인 자바 어노테이션 기반 설정을 보겠습니다.
예제: 간단한 서비스와 컨트롤러
// 서비스 클래스
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
public String getMessage() {
return "Hello, Spring!";
}
}
// 컨트롤러 클래스
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
private final ExampleService exampleService;
@Autowired
public ExampleController(ExampleService exampleService) {
this.exampleService = exampleService;
}
@GetMapping("/message")
public String getMessage() {
return exampleService.getMessage();
}
}
@Service: 이 클래스가 스프링 프레임워크에 의해 관리되는 서비스 클래스임을 표시합니다.
@RestController: 이 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타냅니다.
@Autowired: 스프링이 ExampleService 인스턴스를 자동으로 주입(Injection)하도록 합니다.
2. Spring Boot Application
스프링 부트는 설정을 자동화하여 매우 쉽게 애플리케이션을 시작할 수 있습니다.
예제: 스프링 부트 애플리케이션 설정
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication: 스프링 부트의 자동 설정, 컴포넌트 스캔, 설정을 적용합니다.
SpringApplication.run(...): 애플리케이션을 실행합니다.
3. Spring MVC Controller
스프링 MVC는 웹 애플리케이션에서 HTTP 요청을 처리하는 강력한 웹 프레임워크입니다.
예제: 간단한 MVC 컨트롤러
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class WebController {
@GetMapping("/welcome")
public String welcome(Model model) {
model.addAttribute("message", "Welcome to Spring MVC!");
return "welcome"; // 반환 값은 뷰의 이름입니다.
}
}
@Controller: 이 클래스가 웹 컨트롤러로 동작할 것임을 나타냅니다.
Model: 뷰에 데이터를 전달하기 위해 사용되는 객체입니다.
"welcome": src/main/resources/templates/ 디렉토리에 저장된 뷰 파일의 이름입니다(예: welcome.html).
4. Spring Configuration
스프링 설정은 XML 또는 자바 기반(@Configuration)으로 정의할 수 있습니다. 자바 기반 설정을 사용하면 타입 안전성과 IDE 지원을 받을 수 있습니다.
예제: 자바 기반 설정
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public ExampleService exampleService() {
return new ExampleService();
}
}
@Configuration: 이 클래스가 스프링 설정을 위한 것임을 나타냅니다.
@Bean: 메서드가 스프링 컨테이너에 의해 관리되는 빈(bean) 객체를 생성함을 나타냅니다.
이러한 기능들은 스프링을 통해 복잡한 엔터프라이즈 애플리케이션을 쉽게 개발할 수 있도록 도와줍니다. 추가적인 스프링의 기능으로는 트랜잭션 관리, 보안 설정, RESTful 웹 서비스 개발 등이 있으며, 이는 더 깊은 학습이 필요합니다.