亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在應用程序上下文初始化事件中添加鉤子?

如何在應用程序上下文初始化事件中添加鉤子?

RISEBY 2019-11-28 13:07:07
對于常規的Servlet,我想您可以聲明一個上下文偵聽器,但是對于Spring MVC,Spring可以使此過程變得更容易嗎?此外,如果定義了上下文偵聽器,然后需要訪問在servlet.xml或中定義的bean,我applicationContext.xml將如何訪問它們?
查看完整描述

3 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

從Spring 4.2開始,您可以使用@EventListener(文檔)


@Component

class MyClassWithEventListeners {


    @EventListener({ContextRefreshedEvent.class})

    void contextRefreshedEvent() {

        System.out.println("a context refreshed event happened");

    }

}


查看完整回答
反對 回復 2019-11-28
?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

創建您的注釋


  @Retention(RetentionPolicy.RUNTIME)

    public @interface AfterSpringLoadComplete {

    }

建立課程


    public class PostProxyInvokerContextListener implements ApplicationListener<ContextRefreshedEvent> {


    @Autowired

    ConfigurableListableBeanFactory factory;


    @Override

    public void onApplicationEvent(ContextRefreshedEvent event) {

        ApplicationContext context = event.getApplicationContext();

        String[] names = context.getBeanDefinitionNames();

        for (String name : names) {

            try {

                BeanDefinition definition = factory.getBeanDefinition(name);

                String originalClassName = definition.getBeanClassName();

                Class<?> originalClass = Class.forName(originalClassName);

                Method[] methods = originalClass.getMethods();

                for (Method method : methods) {

                    if (method.isAnnotationPresent(AfterSpringLoadComplete.class)){

                        Object bean = context.getBean(name);

                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());

                        currentMethod.invoke(bean);

                    }

                }

            } catch (Exception ignored) {

            }

        }

    }

}

通過@Component注釋或在xml中注冊此類


<bean class="ua.adeptius.PostProxyInvokerContextListener"/>

并在環境初始化后要在任何要使用的方法上使用注解,例如:


   @AfterSpringLoadComplete

    public void init() {}


查看完整回答
反對 回復 2019-11-28
  • 3 回答
  • 0 關注
  • 566 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號