2022-04-06 TIL

이창호·2022년 4월 6일
0

프로그래머스 백엔드 데브코스 17일차

SpringBoot Part1

DI(Dependency Injection) 방법

  • consturcter base DI
    - IoC Container에서 만든 Bean을 다른 Bean에 쓰이도록 한다.
    • Circular Reference를 조심해야 한다.
@Component
public class BeanA {
	private BeanB b;
    
    public BeanA(BeanB b) {
    	this.b = b;
    }
}
  • setter base DI
@Component
public class BeanA {
	private BeanB b;
    
    public void setBeanB(BeanB b) {
    	this.b = b;
	}
}
  • autowired base DI
@Component
public class BeanA {
	@Autowired
	private BeanB b
}

Component Scan

  • Stereotype Annotation을 이용하여 스캔 대상 지정
  • 설정 Class에서 따로 Bean을 등록 하지 않아도 Bean 등록 가능
  • @ComponenetScan
@Configuration
@ComponentScan(basePackages = {"org.prgrms.kdt.order", "org.prgrms.kdt.voucher", "org.prgrms.kdt.configuration"})

AutoWired

  • 생성자가 2개 이상일 경우 Autowired Annotation으로 명시해줘야함.

Primary

  • 같은 인터페이스를 상속받은 빈이 2개 이상 있을 때, 우선순위를 정해줌

Qualifier

  • Primary와 비슷하지만 용도에 따라 어떤 Bean을 쓸지 명시할 수 있음
	@Qualifier("jdbc")
    
    public TestService(@Qualifier("jdbc") ... ) { ... }
    
    BeanFactoryAnnotationUtils.qualifiedBeanOfType(applicationContext.getBeanFactory(), TestRepository.class, "memory");

Primary, Qualifier ?

  • 보통 Primary를 쓰는편
  • Qualifier는 정말 필요한 경우에만 사용

Bean Scope

  • singleton, prototype, reqeust, session, application, websocket
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class Test { ... }

Bean Lifes Cycle

생성 생명주기 콜백

1. Invoke method @postConstruct with annotated
2. If Bean implements InitializationBean interface, call afterPropertiesSet
3. Invoke method set in initMethod of @Bean.

소멸 생명주기 콜백

1. Invoke method @PreDestroy With annotated
2. If Bean implements DisposableBean interface, call destroy
3. Invoke  method set in destroyMethod of @Bean

그외 꿀팁

ConcurrentHashMap

Multi-thread 환경에서 thread safe를 위해 사용함.

Optional.ofNullable

인자값이 null이라면 비어있는 Optional 객체를 반환한다.

@ComponentScan(basePackageClasses, baskPackages, excludeFilters, includeFilters)

클래스별, 패키지별, 스캔에 포함되지 않는 필터, 스캔에 포함되는 필터를 설정 할 수 있다.
profile
이타적인 기회주의자

0개의 댓글