Spring Framework 입문
Spring의 주요 기능 3가지 : IoC, AOP, PSA
IoC (Inversion of Control) : 제어권이 뒤바뀌었다.
내가 사용할 기능을 내가 만들지 않고 다른 클래스에 만들어진 기능을 이용 할 건데(의존성)
선언은 해 놓았는데 누군가 알아서 넣어주겠지
class OwnerController{
private OwnerRepository repo;
public OwnerController(OwnerRepository repo){
this.repo = repo;
}
}
- 의존성을 풀이하자면 무슨 의미일까? : 기능을 수행하는데 있어서 완벽하게 하기 위해서는 부수적인 기능이 있어야 가능할 경우 부수적인 기능에 의존하고 있음을 알 수 있다.
- 선언을 private로 해 놓은 이유는? : OwnerRepository로 선언한 이 기능은 현재 클래스에서만 이용하고 다른 클래스에서 이용하지 못하도록 하기 위해
- 스프링 프레임워크는 IoC Container에서 관리하는 Bean의 주입이 필요한 특정한 생성자나 어노테이션(@Autowired)이 있을 경우에 필요한 Bean을 의존성으로 자동 주입 되도록 지원하고 있다.
- Spring 4.3 버전부터 클래스의 생성자가 하나뿐이고 생정자를 주입받는 레퍼런스 변수가 Bean으로 등록되어 있을 경우 자동으로 주입 받도록 되어있다.
- DI (Dependency Injection) : 의존성을 주입하는 행위
IoC Container
스프링이 제공하는 ApplicationContext에 속해있다.
ApplicationContext > BeanFactory == IoC Container
빈(bean)을 만들고 엮어주며 제공해준다.
- 만들고
- 엮고
- 제공한다
class Controller{
private final ApplicationContext applicationContext;
private final BeanFactory beanFactory;
private final Repository repository;
public Controller(ApplicationContext applicationContext, BeanFactory beanFactory, Repository repository){
this.applicationContext = applicationContext;
this.beanFactory = beanFactory;
this.repository = repository;
}
@GetMapping("/bean")
@ResponseBody
public String bean(){
return "ApplicationContext: " + applicationContext.getBean(Repository.class) + "\n BeanFactory" + this.beanFactory.getBean(Repository.class) + "\n Repository: " + this.repository + ;
}
}
/* 출력, 아래 3가지의 참조값은 모두 같다.
ApplicationContext: 패키지명@참조값
BeanFactory : 패키지명@참조값
Repository: 패키지명@참조값
즉, Spring IoC Container는 Singleton Scope 라는 뜻이다.
*/
- Singleton Scope : 객체 하나를 생성하여 애플리케이션 전반에서 재사용한다.
- 의존성 자동 주입이란?
IoC Container에 객체로 등록되어 있는 Bean을 .getBean()으로 가져오는 행위를 자동으로 해준다.
Bean
Bean이란 객체라는 뜻과 같다. 다만 IoC Container에 속하는 객체이다.
즉 아래와 같다
// 일반 객체
Controller con = new Controller();
// IoC 객체
Controller con = ApplicationContext.getBean(클래스네임.class);
Bean으로 어떻게 등록하나?
- Component Scanning
- @Component
- @Controller
- @Repository
- @Service
- @Configuration
- 등등
- @Component
- 직접 일일히 등록하는 방법
- XML으로 등록
- 자바 설정 파일 Configuration에서 @Bean으로 등록
Spring IoC Container에 Bean으로 등록하는 여러가지 Interface가 있는데 이를 "Life Cycle Call Back"이라 부른다. 이 중에는 Component를 찾아서 Bean으로 등록하는 Annotation 처리기가 등록되어 있다.
@SpringBootApplication 안에 @ComponentScan이 있는데 이 위치부터 "Component를 찾아라"라는 뜻을 가지고 있다.
Bean을 어떻게 꺼내 쓰나?
- @Autowird 또는 @Inject
- ApplicationContext에서 getBean()으로 직접 꺼내거나
DI(Dependency Injection) 의존성 주입, 3가지 방법
Spring Framework에서는 Constructor Injection 주입 방법을 권장한다.
Constructor Injection
- 클래스가 필수적으로 사용해야 하는 레퍼런스를 강제하여 주입한다.
Field Injection, Setter Injection
- 의존성이 없어도 생성할 수 있다.
- 다만 순환 참조가 발생해 에러가 발생할 수 있다.
Constructor
class Test{
private final TestRepository testRepository;
public Test(TestRepository testRepository){
this.testRepository = testRepository;
}
}
또는
@RequiredArgsConstructor
class Test{
private final TestRepository testRepository;
}
Field
class Test{
@Autowired
private TestRepository testRepository;
}
Setter
class Test{
private TestRepository testRepository;
@Autowired
public void setTestRespository(TestRepository testRepository){
this.testRepository = testRepository;
}
}
AOP (Aspect Oriented Programming) :관점 지향 프로그래밍
비약적인 예시를 들어보자. 약 1000개의 메소드에서 (A)라는 동일한 기능을 하는 코드를 작성하여 사용하는데, 만약 이 (A)라는 기능을 수정해야 한다면 (A) 기능이 적용된 약 1000개의 모든 파일을 전부 찾아다니며 수정하는 과정을 할 것인가?에 대한 고민을 해결해준다.
즉 동일하게 사용되는 기능을 따로 클래스, 메소드로 만들어 두어 특정 클래스, 메소드 등이 수행될 때 해당 AOP 기능을 전, 후로 적용할 수 있다.
AOP 구현 방법
- 컴파일
- A.java → (AOP) → A.class (AspectJ)
- 바이트 코드 조작
- A.java → A.class → (AOP) → 메모리 (AspectJ)
- 프록시 패턴 (스프링 AOP)
PSA (Portable Service Abstraction) : 잘 만든 인터페이스
Spring Framework는 Servlet 기술을 사용하고 있다.
하지만 코드 작성함에 있어 Servlet을 사용하지 않고 @GetMapping @PostMapping과 같은 방식으로 URL을 통해 들어온 내역을 처리한다. 이렇게 실제 사용하는 Servlet 기법은 숨기고 추상화 기법을 사용해 Spring에서 제공하는 개발자에게 편의성 있는 코드로 작성 방법을 사용하는 것이 Service Abstraction 이다.
즉, 아래와 같이 다양한 언어로 작성된 기술을 읽어도 스프링에서 사용하는 코드 하나로 적용되어 사용하기에 코드를 거의 변경하지 않고 편의성 있게 개발할 수 있다.
- Servlet language → Spring → @GetMapping
- Netty language → Spring → @GetMapping
- Jetty language → Spring → @GetMapping
PSA에 해당하는 것은 무엇이 있을까?
- Spring Web MVC
- @Component
- @Controller
- @Repository
- @Service
- @RequestMapping
- 등등
- @Component
- Spring Transaction
- JDBC
- JPA
- Spring Cache
- Cacheable
- CacheEvict
- 등등
참고
인프런 - 예제로 배우는 스프링 입문 (개정판)
'Software Backend > Java & Spring' 카테고리의 다른 글
에러, 서블릿 [app]을(를) 위한 Servlet.init() 호출이 예외를 발생시켰습니다. (0) | 2021.09.11 |
---|---|
자바 기초 다지기 - 5 ( Generic, Collection, Map ) (0) | 2021.09.06 |
자바 기초 다지기 - 4 (내부 클래스, 어노테이션, 자바) (0) | 2021.08.29 |
javap 테스트, for문 안에서 String 문자열 합칠 경우 과연 new 객체를 생성할까? (0) | 2021.08.25 |
자바 new, StringBuilder 메모리 사용량 테스트 (0) | 2021.08.25 |