import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;

@Component
public class TestListener implements ApplicationContextAware,
        ApplicationListener<ApplicationStartedEvent>
{
    private ApplicationContext applicationContext;

    @Autowired
    private ServletContext servletContext;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event)
    {
        //get the container who trigger the event
        ConfigurableApplicationContext c = event.getApplicationContext();
        if (c == applicationContext)
        {
            System.out.println(servletContext);
			System.out.println(servletContext.getContextPath());
        }
        // add in cusomized process.
        System.out.println(servletContext);
        System.out.println(ctx);
    }

    // interface to inject method, and access to Spring container
    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException
    {
        this.ctx = ctx;
    }
}

上述servletContext 包含很多信息,如:context-path等,如下图:
ApplicationContext和ServletContext-LMLPHP

11-17 10:25