동적 bean 정의 변경 내용을 읽었습니다. 간단한 코드 예제 (아래 코드 참조)에서 시도해 보겠습니다. 서버를 멈추고 bean 정의를 추가/변경하고 싶지 않은 상황에서 매우 매력적입니다.스프링 컨텍스트 동적 변경
질문 :
- 그렇게 (아래 코드 참조) 않는 안전한가요?
나는
StaticApplicationContex
또는BeanPostProcessor
또는BeanFactoryPostProcessor
의 도움으로 런타임에 빈 정의 변화를 달성 할 수 있음을 읽은? 그래서 차이점은 무엇입니까?public class Main { final static String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<beans xmlns=\"http://www.springframework.org/schema/beans\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xmlns:context=\"http://www.springframework.org/schema/context\"\n" + " xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd\">\n" + " <context:annotation-config />\n" + " <context:component-scan base-package=\"vbah\"/>"; final static String contextA = "<bean id=\"test\" class=\"java.lang.String\">\n" + "\t\t<constructor-arg value=\"fromContextA\"/>\n" + "</bean></beans>"; final static String contextB = "<bean id=\"test\" class=\"java.lang.String\">\n" + "\t\t<constructor-arg value=\"fromContextB\"/>\n" + "</bean></beans>"; public static void main(String[] args) throws IOException { //create a single context file final File contextFile = new File("src/resources/spring-config.xml"); //write the first context into it FileUtils.writeStringToFile(contextFile, header + contextA); //create a spring context FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( new String[]{contextFile.getPath()} ); //echo "fromContextA" System.out.println(context.getBean("test")); //write the second context into it FileUtils.writeStringToFile(contextFile, header + contextB); //refresh the context context.refresh(); //echo "fromContextB" System.out.println(context.getBean("test")); } }
편집 :
- 내가
BeanPostProcess
을 알고있는 것처럼 이미 수정 래핑하여 런타임에 빈 인스턴스를 존재 할 수 있습니다 :은 아래의 질문에 대답 할 수 프록시를 가지는 오브젝트 내가 맞습니까?
AbstractApplicationContext # refresh() 모든 싱글 톤 빈을 삭제하고 다시 만듭니다.
- 그러나 프로토 타입/사용자 정의 범위 bean의 정의를 변경하려면?
- 만약 내가 두 개의 빈을 가지고 있다면 : A와 B.는 B에 대한 참조를 가지고있다. 빈 정의를 B의 정의를 포함하지 않는 방식으로 변경하면 B 인스턴스는 파괴되지만 새로운 인스턴스 생성되지 않습니다. A보다
null
종속성이 표시됩니다. 내가 맞습니까?
StaticApplicationContext
및BeanFactoryPostProcessor
둘 다 런타임에서 bean 정의를 변경할 수 있습니다. 그러나 차이점은 무엇입니까, 찬성/반대입니까?- [주요 질문] 왜 스프링에는 같은 목표를 달성하는 3 가지 메커니즘이 있습니다.
AbstractApplicationContext#refresh()
,StaticApplicationContext
및BeanFactoryPostProcessor
사이의 간단한 compoarison (또는 사용 예제)을 만들 수 있습니까?
전 대답에 감사드립니다. 제 질문의 * EDIT * 섹션에서 질문에 답변 해 주시기 바랍니다. –
@VolodymyrBakhmatiuk 내 편집을 참조하십시오. –
많은 감사합니다! –