JAVA/spring

[1028 FORM 백기선 스프링프레임워크 핵심기술] IoC 컨테이너와 빈

스프링목차

스프링 IoC Inversion of Control : 제어의 역전: 어떤 객체가 사용하는 의존객체를 직접 만들어 사용하는게 아니라 주입받아 사용. 
- BeanFactory  :스프링 IOC 가장 최상위 인터페이스. 
- 애플리케이션 컴포넌트 중앙저장소
- 빈설정 소스로 부터 빈 정의 읽어드리고 빈구성 제공.
ApplicationContext 
- BeanFactory, 메시지 소스 처리기능, 이벤트 발생기능, 리소스 로딩기능. 
스프링 IoC 컨테이너 빈 인스턴스 생성
의존관계 설정
빈 제공
DI DI(Depedency Injection)의존성 주입.
내부에서 만든 변수를 외부에서 넣어준다.  
객체 생성과 사용자의 관심 분리, 가독성과 재사용을 높혀준다. 
- 광범위한 역제어 테크닉의 한 형태. 
- 클래스는 더이상 객체생성에 대한 책임이 없으며 추상팩토리 디자인 패턴에서 처럼 팩토리객체로 생성을 위임할 필요가 없다. 
스프링 빈 스프링 IoC 컨테이너가 관리하는 객체
의존성 관리
라이프사이클 인터페이스 지원. - @PostConstruct  : 빈이 만들어진후 .호출. 
스코프 : 기본 스프링은 싱글톤으로 만들어 사용
ApplicationContext BeanFactory 상속 받는 인터페이스. 
ClassPathXmlApplicationContext , context:component-scan _ XML 로 스프링 빈생성해서 가져옴. 
--이후 > @Configuration , @Bean , AnnotationConfigApplicationContext();  JAVA로 스프링빈생성
--현재 > @ComponentScan(basePackages="컴포넌트 스캔 시작 클래스")
SpringBootApplication 에 ComponentScan, Configuration이 이미 셋팅. 
스프링 빈 라이프사이클 생성, 의존설정, 사용 소멸. 
- 생산, 설정- 
1. BeanNameAware's 
setBeanName
2. BeanClassLoaderAware's setBeanClassLoader
3. BeanFactoryAware's setBeanFactory
4. ResourceLoaderAware's setResourceLoader (only applicable when running in an application context)
5. ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context)
6. MessageSourceAware's setMessageSource (only applicable when running in an application context)
7. ApplicationContextAware's setApplicationContext (only applicable when running in an application context)
8. ServletContextAware's setServletContext (only applicable when running in a web application context)
9. postProcessBeforeInitialization methods of BeanPostProcessors <<@Autowire
- 초기화-
10. InitializingBean's 
afterPropertiesSet  >> 앞뒤 설정 가능. 
11. a custom init-method definition
- 사용- 
12. postProcessAfterInitialization methods of BeanPostProcessors
- 소멸-
1. DisposableBean's destroy
2. a custom destroy-method definition

* BeamFactory 가 BeanPostProcessor 타입 빈을 찾음 그중 AutowiredAnnotationBeanPostProcessor 를 찾아서.. 일반적인 빈에 적용을 함. 
출처 : BeanFactory docs
@Autowire 필요한 의존 객체의 타입에 해당하는 빈찾아 주입. 
required 기본값 true. 못찾으면 구동실패. 
생성자, 세터, 필드 사용. 

같은타입 빈 여러개 
- @Primary      < 추천. 
- 해당타입 모두 주입 _List<타입> or 필드이름 동일한것을 찾아서 주입 
  BeanPostProcessor 빈초기화 전후>  AutowiredAnnotationBeanPostProcessor(Autowire 처리
- @Qualifer  (빈이름으로 주입 맨앞자 소문자. 변경)
@ComponentScan 스캔 위치 설정 , 필터, 어떤 애노테이션 스캔할지 하지 않을지. 
- basePackages, basePackageClasses
선언 패키지 기준 Class<?>[]basePackageClasses 에 담아 실행.   
- useDefaultFilters, includeFilters, excludeFilters
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
구동시간 bean 늘어남 늘어지는단점. .. 예민하면 펑션 등 고려
실제 스캐닝은 ConfigurationClassPostProcessor라는 BeanFactoryPostProcessor에서 다른빈 모두 등록 전에 처리 됨.
- lazyInit  true 시.. 보통은 바로 초기화,  해당클래스 사용시 초기화. 
@Component @Repository
@Service
@Controller
@Configuration
스프링 빈의 스코프 @Component @Scope("prototype") 
프로토타입 내부 싱글톤 문제없음. 항상동일
싱글톤 내부 프로토 빈 사용시 프로토가 같음... 싱글톤과.. 같은현상. , 기본값 프록시 사용안함
>>@Component @Scope("prototype", proxyMode=ScopeProxyMode.TARGET_CLASS) 
CG라이브러리 사용한 다이나믹 프록시 적용됨. 매번 바꿀수있는 프록시로 감싸도록함. 
ObjectProvider<클래스> 클래스변수이름;

singleton : 스프링 default bean scope
prototype : 애플리케이션 요청시 ( getBean() 메서드가 호출될 때마다) 스프링이 새 인스턴스를 생성합니다
request : HTTP 요청별로 인스턴스화 되며 요청이 끝나면 소멸됩니다
session : HTTP 세션별로 인스턴스화 되며 세션이 끝나면 소멸됩니다.
global session : 포틀릿 기반의 웹 애플리케이션 용도로 전역 세션 스코프가 빈과 같은 스프링 MVC를 사용한 포탈 애플리케이션 내의 모든 포틀릿 사이에 공유를 할 수 있습니다.
thread : 새 스레드에서 요청하면 새로운 bean 인스턴스를 생성합니다. 같은 스레드의 요청에는 항상 같은 인스턴스가 반환됩니다.
custom : org.pringframework.beans.factory.config.Scope를 구현하고 커스텀 스코프를 스프링의 설정에 등록하여 사용합니다.

출처 : [Spring] Bean Scope와 Bean Life Cycle ooeunz.tistory.com/107
POJO Plain Old Java Object :  오래된 방식 자바 오브젝트 : 객체지향 원리 충실  
스프링 PSA POJO 철학 반영, Portable Service Abstraction  환경 변화 관계없이 일관된 환경제공 추상화구조
proxy 인터넷상에서, 한번 요청된 데이터를 저장해 두고 반복 요청 시에 저장된 데이터를 빠르게 제공해 주는 서버.

 

 

 

Inversion of Control

더보기

private BookRepository bookRepository = new BookRepository();   <- 의존객체를 직접만들어 사용

@Autowired                                                                         <-의존객체를 주입받아 사용. 

private BookRepository bookRepository;

public BookService(BookRepository bookRepository){                    

   this.bookRepository = bookRepository;

}

스프링빈 vs 자바빈

더보기
public class Book{                  >> 자바빈
	private int id;
	public int getId(){
		return id ;
	}
    public void setId(int id){
    	this.id;
    }
}                     

@Repository
public class BookRepository{}        >> 스프링 빈   이경우 어노테이션으로 autoscan 으로 빈으로 민들어짐. 

@Configuration , @Bean, AnnotationConfigApplicationContext  사용해서 스프링빈 만들때. 

더보기
@Configuration
 public class  ApplicationConfig{
      @Bean
      public BookRepositoy bookRepository(){
          return new BookRepository();
      }
}
-----
ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);  <<이렇게 사용가능