Spring 상용 인터페이스
                                            
 21030 단어  spring
                    
응용 프로그램 Context 가 실 행 될 때 이 인 터 페 이 스 를 실현 할 수 있 기 를 기대 합 니 다.
/**
 *   Spring ApplicationContextAware  
 * @author zhangwei_david
 * @version $Id: TestApplicationContextAware.java, v 0.1 2015 1 3    11:42:19 zhangwei_david Exp $
 */
@Component
public class TestApplicationContextAware implements ApplicationContextAware {
    /**
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LoggerUtils.info("ApplicationContext runs in");
    }
}
  시작 과정의 로 그 는 다음 과 같 습 니 다.
   03, 2015 11:46:02    org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
  : Bean 'executor' of type [class org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
   03, 2015 11:46:02    org.springframework.scheduling.concurrent.ExecutorConfigurationSupport initialize
  : Initializing ExecutorService  'scheduler'
   03, 2015 11:46:02    org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
  : Bean 'scheduler' of type [class org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
   03, 2015 11:46:02    org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
  : Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@132c619: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,app,asyncDemo,testClient,testApplicationContextAware,executor,scheduler,org.springframework.context.annotation.internalAsyncAnnotationProcessor,org.springframework.context.annotation.internalScheduledAnnotationProcessor,studentBiz,beforeAdvice,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,afterAdvice,helloWord,fileCopier,mbeanExporter,assembler,messageSource,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
11:46:02.886 [main] INFO  com.cathy.demo.util.LoggerUtils - ApplicationContext runs in
   03, 2015 11:46:02    org.springframework.context.support.AbstractApplicationContext prepareRefresh
  : Refreshing org.apache.cxf.bus.spring.BusApplicationContext@121202d: startup date [Sat Jan 03 11:46:02 CST 2015]; root of context hierarchy
   03, 2015 11:46:03    org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
  : Loading XML bean definitions from class path resource [META-INF/cxf/cxf.xml]
   03, 2015 11:46:03    org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
  : Loading XML bean definitions from class path resource [META-INF/cxf/cxf-extension-jaxws.xml]
   03, 2015 11:46:03    org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
  : Loading XML bean definitions from class path resource [META-INF/cxf/cxf-extension-soap.xml]
   03, 2015 11:46:03    org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions  2 BeanNameAware
Bean 이 BeanFactory 에 설 치 된 이름 을 알 고 싶 을 때 이 인 터 페 이 스 를 실현 할 수 있 습 니 다.
/**
 *   BeanNameAware  
 * @author zhangwei_david
 * @version $Id: TestBeanNameAware.java, v 0.1 2015 1 3    11:48:50 zhangwei_david Exp $
 */
@Component(value = "hello")
public class TestBeanNameAware implements BeanNameAware {
    private String beanName;
    /**
     * @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
     */
    public void setBeanName(String name) {
        LoggerUtils.info("setBeanName(" + name + ")");
        beanName = name;
    }
    /**
     * Getter method for property <tt>beanName</tt>.
     *
     * @return property value of beanName
     */
    public String getBeanName() {
        return beanName;
    }
}  결 과 는:
12:10:47.496 [main] INFO com.cathy.demo.util.LoggerUtils - setBeanName(hello)
3. InitializingBean
하면, 만약, 만약... 모든 속성 을 설정 한 후 진일보 한 반응 을 하면 이 인 터 페 이 스 를 실현 할 수 있다.
/**
 *   InitializingBean
 * @author zhangwei_david
 * @version $Id: TestInitializingBean.java, v 0.1 2015 1 3    12:04:38 zhangwei_david Exp $
 */
@Component()
public class TestInitializingBean implements InitializingBean, BeanNameAware {
    private String beanName;
    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        LoggerUtils.info("Bean         :" + beanName);
    }
    /**
     * @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
     */
    public void setBeanName(String name) {
        beanName = name;
    }
}
  결 과 는:
12:10:47.496 [main] INFO com. cathy. demo. util. LoggerUtils - Bean 의 속성 이 모두 설정 되 었 습 니 다. testInitialingBean
Spring 에 서 는 Bean 의 모든 속성 을 성공 적 으로 설정 한 후에 특정한 행 위 를 수행 하 는 두 가지 방식 이 있 습 니 다. InitializingBean 인 터 페 이 스 를 실현 하 는 것 외 에 Spring 의 설정 파일 에서 init - method 속성 을 지정 할 수 있 습 니 다.그렇다면 이 두 가지 가 동시에 실행 되 는 속성 이 존재 한다 면 어떤 것 일 까?
/**
 *    InitializingBean     
 *
 * @author zhangwei_david
 * @version $Id: MyInitTest.java, v 0.1 2015 6 7    5:46:27 zhangwei_david Exp $
 */
public class MyInitTest implements InitializingBean {
    public MyInitTest() {
        System.out.println("------------MyInitTest        -------------");
    }
    public void init() {
        System.out.println("------------spring    initMethod    -------------");
    }
    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        System.out.println("------------InitializingBean.afterPropertiesSet ()     -------------");
    }
}  <bean id="myInitTest" class="com.cathy.demo.spring.MyInitTest"
		init-method="init" />  log4j:WARN custom level class [#   DEBUG       ] not found.
2015-06-07 17:56:47  [ main:0 ] - [ INFO ]  @TestExecutionListeners is not present for class [class com.cathy.demo.spring.MySpringTest]: using defaults.
2015-06-07 17:56:47  [ main:145 ] - [ INFO ]  Loading XML bean definitions from URL [file:/H:/Alipay.com/workspace4alipay/demo/target/classes/META-INF/spring/test-beans.xml]
2015-06-07 17:56:47  [ main:327 ] - [ INFO ]  JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
2015-06-07 17:56:47  [ main:359 ] - [ INFO ]  Refreshing org.springframework.context.support.GenericApplicationContext@15f7ae5: startup date [Sun Jun 07 17:56:47 CST 2015]; root of context hierarchy
2015-06-07 17:56:47  [ main:472 ] - [ INFO ]  Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2db087: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myInitTest,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
------------MyInitTest        -------------
------------InitializingBean.afterPropertiesSet ()     -------------
------------spring    initMethod    -------------
2015-06-07 17:56:47  [ Thread-0:493 ] - [ INFO ]  Closing org.springframework.context.support.GenericApplicationContext@15f7ae5: startup date [Sun Jun 07 17:56:47 CST 2015]; root of context hierarchy
2015-06-07 17:56:47  [ Thread-0:494 ] - [ INFO ]  Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2db087: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myInitTest,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
  로그 에서 알 수 있 듯 이 그들의 실행 순 서 는... afterPropertiesSet()->initMethod()
주 해 를 사용 하 는 방식 으로 initMehthod 를 지정 하 는 방식 은 initMethod () 에 @ PostConstruct 를 추가 하 는 것 입 니 다. 이때 의 집행 순 서 는 이 렇 습 니까?아래 테스트 를 살 펴 보 겠 습 니 다. Spring 설정 파일 에는 bean 설정 이 없습니다.
/**
 *    InitializingBean     
 *
 * @author zhangwei_david
 * @version $Id: MyInitTest.java, v 0.1 2015 6 7    5:46:27 zhangwei_david Exp $
 */
@Component
public class MyInitTest implements InitializingBean {
    public MyInitTest() {
        System.out.println("------------MyInitTest        -------------");
    }
    @PostConstruct
    public void init() {
        System.out.println("------------spring    initMethod    -------------");
    }
    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        System.out.println("------------InitializingBean.afterPropertiesSet ()     -------------");
    }
}  결 과 는:
2015-06-07 18:09:44  [ main:0 ] - [ INFO ]  @TestExecutionListeners is not present for class [class com.cathy.demo.spring.MySpringTest]: using defaults.
2015-06-07 18:09:44  [ main:136 ] - [ INFO ]  Loading XML bean definitions from URL [file:/H:/Alipay.com/workspace4alipay/demo/target/classes/META-INF/spring/test-beans.xml]
2015-06-07 18:09:44  [ main:311 ] - [ INFO ]  JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
2015-06-07 18:09:44  [ main:346 ] - [ INFO ]  Refreshing org.springframework.context.support.GenericApplicationContext@15f7ae5: startup date [Sun Jun 07 18:09:44 CST 2015]; root of context hierarchy
2015-06-07 18:09:44  [ main:480 ] - [ INFO ]  Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1fe3806: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myInitTest,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
------------MyInitTest        -------------
------------spring    initMethod    -------------
------------InitializingBean.afterPropertiesSet ()     -------------
2015-06-07 18:09:44  [ Thread-0:500 ] - [ INFO ]  Closing org.springframework.context.support.GenericApplicationContext@15f7ae5: startup date [Sun Jun 07 18:09:44 CST 2015]; root of context hierarchy
2015-06-07 18:09:44  [ Thread-0:501 ] - [ INFO ]  Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1fe3806: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myInitTest,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
  4. BeanPostProcessor
BeanPostProcessor BeanFactory 의 갈고리 입 니 다. 고객 이 새로 만 든 Bean 을 수정 할 수 있 도록 해 줍 니 다.
/**
 * Test BeanPostProcessor
 * @author zhangwei_david
 * @version $Id: TestBeanPostProcessor.java, v 0.1 2015 1 3    12:14:32 zhangwei_david Exp $
 */
@Component
public class TestBeanPostProcessor implements BeanPostProcessor {
    /**
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
     */
    public Object postProcessBeforeInitialization(Object bean, String beanName)
                                                                               throws BeansException {
        LoggerUtils.info("bean       :bean=" + bean + ", beanName" + beanName);
        return bean;
    }
    /**
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
     */
    public Object postProcessAfterInitialization(Object bean, String beanName)
                                                                              throws BeansException {
        LoggerUtils.info("bean       :bean=" + bean + ", beanName" + beanName);
        return bean;
    }
}
  결 과 는:
12:16:06.314 [main] INFO com.cathy.demo.util.LoggerUtils - ApplicationContext runs in12:16:06.314 [main] INFO com. cathy. demo. util. LoggerUtils - bean 초기 화 전 호출: bean = com. cathy. demo. test.TestApplicationContextAware@f70944, beanNametestApplicationContextAwareafter test for AOP postProcessBeforeInitialization12:16:06.330 [main] INFO com. cathy. demo. util. LoggerUtils - bean 초기 화 후 호출: bean = com. cathy. demo. test.TestApplicationContextAware@f70944, beanNametestApplicationContextAwareafter test for AOP postProcessAfterInitialization12:16:06.330 [main] INFO com.cathy.demo.util.LoggerUtils - setBeanName(hello)12:16:06.330 [main] INFO com. cathy. demo. util. LoggerUtils - bean 초기 화 전 호출: bean = com. cathy. demo. test.TestBeanNameAware@a6bea6, beanNamehelloafter test for AOP postProcessBeforeInitialization12:16:06.330 [main] INFO com. cathy. demo. util. LoggerUtils - bean 초기 화 후 호출: bean = com. cathy. demo. test.TestBeanNameAware@a6bea6, beanNamehelloafter test for AOP postProcessAfterInitialization12:16:06.330 [main] INFO com. cathy. demo. util. LoggerUtils - bean 초기 화 전 호출: bean = com. cathy. demo. test.TestInitializingBean@1b21bd3, beanNametestInitializingBeanafter test for AOP postProcessBeforeInitialization12:16:06.330 [main] INFO com. cathy. demo. util. LoggerUtils - Bean 의 속성 이 모두 설정 되 었 습 니 다. testInitialingBean 12: 16: 06.346 [main] INFO com. cathy. demo. util. LoggerUtils - bean 초기 화 후 호출: bean = com. cathy. demo. test.TestInitializingBean@1b21bd3, beanNametestInitializingBeanafter test for AOP postProcessAfterInitialization
/**
 *    InitializingBean     
 *    BeanPostProcessor  
 *
 * @author zhangwei_david
 * @version $Id: MyInitTest.java, v 0.1 2015 6 7    5:46:27 zhangwei_david Exp $
 */
@Component
public class MyInitTest implements InitializingBean, BeanPostProcessor {
    private Person man;
    public MyInitTest() {
        System.out.println("------------MyInitTest        -------------");
    }
    @PostConstruct
    public void init() {
        System.out.println("------------spring    initMethod    -------------");
    }
    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        System.out.println("------------InitializingBean.afterPropertiesSet ()     -------------");
    }
    /**
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
     */
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("--------- " + beanName
                           + "        postProccessBeforeInitializaiton--------");
        return bean;
    }
    /**
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
     */
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("--------- " + beanName
                           + "         postProcessAfterInitialization--------");
        return bean;
    }
    /**
     * Setter method for property <tt>man</tt>.
     *
     * @param man value to be assigned to property man
     */
    @Autowired
    public void setMan(Person man) {
        System.out.println("      man=" + man.getSex());
        this.man = man;
    }
}  ------------MyInitTest        -------------
2015-06-07 18:49:55  [ main:480 ] - [ INFO ]  Bean 'man' of type [class com.cathy.demo.spring.Man] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
      man=Male
------------spring    initMethod    -------------
------------InitializingBean.afterPropertiesSet ()     -------------
2015-06-07 18:49:55  [ main:492 ] - [ INFO ]  Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@de0926: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myInitTest,man,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
--------- com.cathy.demo.spring.MySpringTest        postProccessBeforeInitializaiton--------
--------- com.cathy.demo.spring.MySpringTest         postProcessAfterInitialization--------
2015-06-07 18:49:55  [ Thread-0:506 ] - [ INFO ]  Closing org.springframework.context.support.GenericApplicationContext@115b42e: startup date [Sun Jun 07 18:49:55 CST 2015]; root of context hierarchy
2015-06-07 18:49:55  [ Thread-0:507 ] - [ INFO ]  Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@de0926: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myInitTest,man,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
  이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.