下面列出了org.springframework.context.ApplicationContext#publishEvent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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());
}
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);
}
@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());
}
@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));
}
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
}
@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());
}
/**
* 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;
}
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();
}
@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));
}
}
/**
* 健康检查
*
* @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();
}
@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());
}
/**
*
* {@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));
}
}
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));
}
/**
* 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");
}
/**
* 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));
}