스프링Spring
[Spring] 스프링 BeanPostProcessor
개린이9999
2023. 1. 12. 07:48
728x90
BeanPostProcessor
Bean 객체를 정의할 때 init-method 속성을 설정하면 객체가 생성될 때 자동으로 호출될 메서드를 지정할 수 있다.
이때 BeanPostProcessor 인터페이스를 구현한 클래스를 정의하면 Bean 객체를 생성할 때 호출될 init 메서드 호출을 가로채 다른 메서드를 호출할 수 있도록 할 수 있다.
Spring에서는 객체가 생성될 때 init-method로 지정된 메서드가 호출되기 전, 후에 다른 메서드를 호출할수 있도록 지원하고 있다.
관련예제 ↓
메인클래스
package sanghoon.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sanghoon.beans.TestBean1;
import sanghoon.beans.TestBean2;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext ctx= new ClassPathXmlApplicationContext("sanghoon/config/beans.xml");
TestBean1 t1 = ctx.getBean("t1",TestBean1.class);
System.out.printf("t1: %s\n",t1);
System.out.println("-----------------------------------");
TestBean2 t2 = ctx.getBean("t2",TestBean2.class);
System.out.printf("t2: %s\n",t2);
ctx.close();
}
}
package sanghoon.beans;
public class TestBean1 {
public TestBean1() {
System.out.println("TestBean1의 생성자");
}
public void bean1_init() {
System.out.println("TestBean1의 init 메서드");
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id='t1' class= 'sanghoon.beans.TestBean1' lazy-init='true' init-method="bean1_init"/>
<bean id='t2' class= 'sanghoon.beans.TestBean2' lazy-init='true' init-method="bean2_init"/>
<bean class='sanghoon.processor.TestBeanPostProcessor'/>
</beans>
package sanghoon.beans;
public class TestBean2 {
public TestBean2() {
System.out.println("TestBean2의 생성자");
}
public void bean2_init() {
System.out.println("TestBean2의 init 메서드");
}
}
TestBeanPostProcessor
package sanghoon.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class TestBeanPostProcessor implements BeanPostProcessor{
//init-method 호출 전
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("before");
switch(beanName) {
case"t1" :
System.out.println("id가 t1인 bean객체 생성");
break;
case"t2" :
System.out.println("id가 t2인 bean객체 생성");
break;
}
return bean;
}
//init-method 후
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("after");
return bean;
}
}
728x90