Java Code Examples for org.springframework.context.ApplicationContext#publishEvent()

The following examples show how to use org.springframework.context.ApplicationContext#publishEvent() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void testBootstrapAndShutdown() throws Exception
{
    // now bring up the bootstrap
    ApplicationContext ctx = new ClassPathXmlApplicationContext(APP_CONTEXT_XML);
    
    // the folder should be gone
    assertFalse("Folder was not deleted by bootstrap", dir.exists());
    
    // now create the folder again
    dir.mkdir();
    assertTrue("Directory not created", dir.exists());
    
    // announce that the context is closing
    ctx.publishEvent(new ContextClosedEvent(ctx));
    
    // the folder should be gone
    assertFalse("Folder was not deleted by shutdown", dir.exists());
}
 
Example 2
Source Project: lemon   File: LogoutHttpSessionListener.java    License: Apache License 2.0 6 votes vote down vote up
public void sessionDestroyed(HttpSessionEvent se) {
    ApplicationContext ctx = WebApplicationContextUtils
            .getWebApplicationContext(se.getSession().getServletContext());

    if (ctx == null) {
        logger.warn("cannot find applicationContext");

        return;
    }

    HttpSession session = se.getSession();
    UserAuthDTO userAuthDto = this.internalUserAuthConnector
            .findFromSession(session);

    String tenantId = null;

    if (userAuthDto != null) {
        tenantId = userAuthDto.getTenantId();
    }

    LogoutEvent logoutEvent = new LogoutEvent(session, null,
            session.getId(), tenantId);
    ctx.publishEvent(logoutEvent);
}
 
Example 3
@Test
public void applicationEventListener() {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass());
	Messenger eventListener = (Messenger) ctx.getBean("eventListener");
	ctx.publishEvent(new MyEvent(ctx));
	assertEquals("count=2", eventListener.getMessage());
}
 
Example 4
@Test
public void testEventClassWithInterface() {
	ApplicationContext ac = new AnnotationConfigApplicationContext(AuditableListener.class);
	AuditablePayloadEvent event = new AuditablePayloadEvent<>(this, "xyz");
	ac.publishEvent(event);
	assertTrue(ac.getBean(AuditableListener.class).events.contains(event));
}
 
Example 5
Source Project: spring-analysis-note   File: EventBootstrap.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
	ApplicationContext context = new ClassPathXmlApplicationContext("factory.bean/bean-post-processor.xml");
	// 第一个参数是来源,第二个参数是自定义
	CarEvent carEvent = new CarEvent("hello",  "world");
	context.publishEvent(carEvent);
	// 消息发送之后,打印以下内容
	// source : hello,  custom message : world
}
 
Example 6
@Test
public void applicationEventListener() {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass());
	Messenger eventListener = (Messenger) ctx.getBean("eventListener");
	ctx.publishEvent(new MyEvent(ctx));
	assertEquals("count=2", eventListener.getMessage());
}
 
Example 7
/**
 * Static helper that can be used to exit a {@link SpringApplication} and obtain a
 * code indicating success (0) or otherwise. Does not throw exceptions but should
 * print stack traces of any encountered. Applies the specified
 * {@link ExitCodeGenerator} in addition to any Spring beans that implement
 * {@link ExitCodeGenerator}. In the case of multiple exit codes the highest value
 * will be used (or if all values are negative, the lowest value will be used)
 * @param context the context to close if possible
 * @param exitCodeGenerators exist code generators
 * @return the outcome (0 if successful)
 */
public static int exit(ApplicationContext context,
		ExitCodeGenerator... exitCodeGenerators) {
	Assert.notNull(context, "Context must not be null");
	int exitCode = 0;
	try {
		try {
			ExitCodeGenerators generators = new ExitCodeGenerators();
			Collection<ExitCodeGenerator> beans = context
					.getBeansOfType(ExitCodeGenerator.class).values();
			generators.addAll(exitCodeGenerators);
			generators.addAll(beans);
			exitCode = generators.getExitCode();
			if (exitCode != 0) {
				context.publishEvent(new ExitCodeEvent(context, exitCode));
			}
		}
		finally {
			close(context);
		}
	}
	catch (Exception ex) {
		ex.printStackTrace();
		exitCode = (exitCode != 0) ? exitCode : 1;
	}
	return exitCode;
}
 
Example 8
Source Project: blog   File: PersonTest.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
	System.out.println("开始初始化容器");
	ApplicationContext ac = new ClassPathXmlApplicationContext("person.xml");
	System.out.println("xml加载完毕");
	PersonBean person1 = (PersonBean) ac.getBean("person1");
	System.out.println(person1);
	PersonBean person2 = (PersonBean) ac.getBean("person2");
	System.out.println(person2);
	System.out.println("关闭容器");

	EmailEvent event = new EmailEvent("hello", "[email protected]", "This is a test");
	ac.publishEvent(event);

	((ClassPathXmlApplicationContext) ac).close();
}
 
Example 9
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextRefreshedEvent) {

        ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
        //rpc 开始启动事件监听器
        applicationContext.publishEvent(new SofaBootRpcStartEvent(applicationContext));

        //rpc 启动完毕事件监听器
        applicationContext.publishEvent(new SofaBootRpcStartAfterEvent(applicationContext));
    }
}
 
Example 10
/**
 * 健康检查
 *
 * @param applicationContext Spring 上下文
 * @return 健康检查结果
 */
@Override
public Health onHealthy(ApplicationContext applicationContext) {
    Health.Builder builder = new Health.Builder();

    //rpc 开始启动事件监听器
    applicationContext.publishEvent(new SofaBootRpcStartEvent(applicationContext));

    //rpc 启动完毕事件监听器
    applicationContext.publishEvent(new SofaBootRpcStartAfterEvent(applicationContext));

    return builder.status(Status.UP).build();
}
 
Example 11
@Test
public void applicationEventListener() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass());
	Messenger eventListener = (Messenger) ctx.getBean("eventListener");
	ctx.publishEvent(new MyEvent(ctx));
	assertEquals("count=2", eventListener.getMessage());
}
 
Example 12
/**
 *
 * {@inheritDoc}
 */
@Override
public void onApplicationEvent(final ContextRefreshedEvent event)
{
    if (this.extendedEventParameters == null)
    {
        this.extendedEventParameters = Collections.<String, Serializable> emptyMap();
    }

    if (event.getSource() == this.applicationContext)
    {
        final ApplicationContext context = event.getApplicationContext();
        context.publishEvent(new ContentStoreCreatedEvent(this, this.extendedEventParameters));
    }
}
 
Example 13
Source Project: onetwo   File: Springs.java    License: Apache License 2.0 5 votes vote down vote up
public static void initApplication(ApplicationContext applicationContext) {
	Assert.notNull(applicationContext, "applicationContext can not be null");
	instance.appContext = applicationContext;
	instance.initialized = true;
	instance.printBeanNames();
	if(ConfigurableApplicationContext.class.isInstance(applicationContext)){
		((ConfigurableApplicationContext)applicationContext).registerShutdownHook();
	}
	applicationContext.publishEvent(new SpringsInitEvent(applicationContext));
}
 
Example 14
Source Project: microcks   File: MockControllerCommons.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Publish a mock invocation event on Spring ApplicationContext internal bus.
 * @param applicationContext The context to use for publication
 * @param eventSource The source of this event
 * @param service The mocked Service that was invoked
 * @param response The response is has been dispatched to
 * @param startTime The start time of the invocation
 */
public static void publishMockInvocation(ApplicationContext applicationContext, Object eventSource, Service service, Response response, Long startTime) {
   // Publish an invocation event before returning.
   MockInvocationEvent event = new MockInvocationEvent(eventSource, service.getName(), service.getVersion(),
         response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
   applicationContext.publishEvent(event);
   log.debug("Mock invocation event has been published");
}
 
Example 15
/**
 * Publishes an event to the application context that will notify any interested parties of the existence of this
 * content store.
 * 
 * @param context
 *            the application context
 * @param extendedEventParams 
 */
private void publishEvent(ApplicationContext context, Map<String, Serializable> extendedEventParams)
{
    context.publishEvent(new ContentStoreCreatedEvent(this, extendedEventParams));
}