-
Notifications
You must be signed in to change notification settings - Fork 0
4주차 스터디 내용 정리
JasonYoo1995 edited this page Aug 2, 2021
·
6 revisions
<context:component-scan>
가 <context:annotation-config>
보다 더 넓은 scan을 한다.
<context:component-scan>
을 하면 <context:annotation-config>
를 할 필요가 없다.
<context:annotation-config>
만 하려면 xml이나 @Configuration
클래스에 bean을 미리 선언해놔야 한다.
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="destructiveBean"
class="DestructiveBean"
destroy-method="destroy"/>
</beans>
import org.springframework.context.support.GenericXmlApplicationContext;
public class DestructiveBean {
public void destroy(){
System.out.println("destroy() invoked");
}
public static void main(String[] args) throws Exception{
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("destroy_test.xml");
ctx.refresh();
DestructiveBean bean = (DestructiveBean) ctx.getBean("destructiveBean");
System.out.println("shutdown hook is registered on ctx");
ctx.registerShutdownHook();
System.out.println("before ctx.destroy()");
ctx.close();
System.out.println("after ctx.destroy()");
int sec = 0;
while(sec<=5){
Thread.sleep(1000);
System.out.println(++sec);
if(sec==3){
System.exit(1); // 강제 종료
}
}
System.out.println("End of the program");
}
}
ApplicationContext.destroy()는 deprecated 됐고 ApplicationContext.close()를 쓴다.
new를 통해 생성할 수 없는 객체, 즉 '생성자/수정자/필드' 주입으로 의존성을 관리할 수 없는 객체는
FactoryBean
과 Wrapping을 통해 빈으로 만들 수 있다.
따라서 FactoryBean
과 @Configuration
는 모든 종류의 객체를 IoC 컨테이너가 관리할 수 있는 빈으로 만들어준다는 공통점이 있지만
FactoryBean
보다는 @configuration
(자바 구성 클래스 방식)을 더 권장한다.
그 이유는 FactoryBean
의 메서드를 Overriding하여 복잡하게 구현하지 않아도 되고, 코드 작성도 더 간단하기 때문이다.