Java 类org.springframework.web.context.ContextLoader 实例源码

项目:solo-spring    文件:AbstractPlugin.java   
/**
 * Reads lang_xx.properties into field {@link #langs langs}.
 */
public void readLangs() {
    final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

    final Set<String> resourcePaths = servletContext.getResourcePaths("/plugins/" + dirName);

    for (final String resourcePath : resourcePaths) {
        if (resourcePath.contains("lang_") && resourcePath.endsWith(".properties")) {
            final String langFileName = StringUtils.substringAfter(resourcePath, "/plugins/" + dirName + "/");

            final String key = langFileName.substring("lang_".length(), langFileName.lastIndexOf("."));
            final Properties props = new Properties();

            try {
                final File file = Latkes.getWebFile(resourcePath);

                props.load(new FileInputStream(file));

                langs.put(key.toLowerCase(), props);
            } catch (final Exception e) {
                logger.error("Get plugin[name=" + name + "]'s language configuration failed", e);
            }
        }
    }
}
项目:solo-spring    文件:Skins.java   
/**
 * Gets all skin directory names. Scans the /skins/ directory, using the
 * subdirectory of it as the skin directory name, for example,
 * 
 * <pre>
 * ${Web root}/skins/
 *     <b>default</b>/
 *     <b>mobile</b>/
 *     <b>classic</b>/
 * </pre>
 * 
 * .
 *
 * @return a set of skin name, returns an empty set if not found
 */
public static Set<String> getSkinDirNames() {
    final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

    final Set<String> ret = new HashSet<>();
    final Set<String> resourcePaths = servletContext.getResourcePaths("/skins");

    for (final String path : resourcePaths) {
        final String dirName = path.substring("/skins".length() + 1, path.length() - 1);

        if (dirName.startsWith(".")) {
            continue;
        }

        ret.add(dirName);
    }

    return ret;
}
项目:lams    文件:SpringBeanAutowiringSupport.java   
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
    Assert.notNull(target, "Target object must not be null");
    WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
    if (cc != null) {
        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
        bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
        bpp.processInjection(target);
    }
    else {
        if (logger.isDebugEnabled()) {
            logger.debug("Current WebApplicationContext is not available for processing of " +
                    ClassUtils.getShortName(target.getClass()) + ": " +
                    "Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
        }
    }
}
项目:spring4-understanding    文件:SpringBeanAutowiringSupport.java   
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
    Assert.notNull(target, "Target object must not be null");
    WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
    if (cc != null) {
        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
        bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
        bpp.processInjection(target);
    }
    else {
        if (logger.isDebugEnabled()) {
            logger.debug("Current WebApplicationContext is not available for processing of " +
                    ClassUtils.getShortName(target.getClass()) + ": " +
                    "Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
        }
    }
}
项目:spring4-understanding    文件:Spr8510Tests.java   
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocation("programmatic.xml");
    ContextLoaderListener cll = new ContextLoaderListener(ctx);

    MockServletContext sc = new MockServletContext();
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

    try {
        cll.contextInitialized(new ServletContextEvent(sc));
        fail("expected exception");
    } catch (Throwable t) {
        // assert that an attempt was made to load the correct XML
        assertTrue(t.getMessage(), t.getMessage().endsWith(
                "Could not open ServletContext resource [/from-init-param.xml]"));
    }
}
项目:spring4-understanding    文件:Spr8510Tests.java   
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
    ContextLoaderListener cll = new ContextLoaderListener(ctx);

    MockServletContext sc = new MockServletContext();
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

    try {
        cll.contextInitialized(new ServletContextEvent(sc));
        fail("expected exception");
    } catch (Throwable t) {
        // assert that an attempt was made to load the correct XML
        assertTrue(t.getMessage().endsWith(
                "Could not open ServletContext resource [/from-init-param.xml]"));
    }
}
项目:spring4-understanding    文件:Spr8510Tests.java   
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
    XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
        @Override
        protected String[] getDefaultConfigLocations() {
            return new String[] { "/WEB-INF/custom.xml" };
        }
    };
    //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
    ContextLoaderListener cll = new ContextLoaderListener(ctx);

    MockServletContext sc = new MockServletContext();
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

    try {
        cll.contextInitialized(new ServletContextEvent(sc));
        fail("expected exception");
    } catch (Throwable t) {
        // assert that an attempt was made to load the correct XML
        System.out.println(t.getMessage());
        assertTrue(t.getMessage().endsWith(
                "Could not open ServletContext resource [/from-init-param.xml]"));
    }
}
项目:rocketMqCurrency    文件:MqConsumerController.java   
/**
 *  销毁一个消费端 
 *  
 *     该方法  会通过传递的   ConsumerID 从 servletContext 查询 是否有 该对象 
 *     然后调用 其销毁方法 
 * 
 * @param ConsumerID    消费者唯一标识   
 * @return   
 */
@RequestMapping(method = RequestMethod.DELETE)
public ResponseEntity<String> destroyMqConsumer(@RequestParam("Consumer") String Consumer)
{

    ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext()
            .getServletContext();
    @SuppressWarnings("unchecked")
    Enumeration<String> attributeNames = servletContext.getAttributeNames();

    List<String> outList = new ArrayList<String>();

    Object AttributeConsumer = servletContext.getAttribute(Consumer);
    if (AttributeConsumer != null)
    {
        MqConsumer mqConsumer = (MqConsumer) AttributeConsumer;
        mqConsumer.destroy();
        servletContext.setAttribute(Consumer, null);

        return ResponseEntity.status(HttpStatus.OK).body(Consumer + " 消费者销毁成功");
    }

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Consumer + " 未找到   该消费者 ");
}
项目:rocketMqCurrency    文件:MqConsumerController.java   
/**
 * 获取servletContext 中存放的 所有  消费者对象 唯一标识 
 * 
 * @return  返回  说有消费者唯一标识  
 * 
 */
@RequestMapping(method = RequestMethod.GET)
public List<AttributeNames> queryMqConsumerList()
{
    ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext()
            .getServletContext();

    List<AttributeNames> list = new ArrayList<AttributeNames>();
    Enumeration<String> attributeNames = servletContext.getAttributeNames();
    while (attributeNames.hasMoreElements())
    {
        String nameString = (String) attributeNames.nextElement();
        if (nameString.contains("@"))
        {
            AttributeNames attri = new AttributeNames();
            attri.setKid(nameString);
            list.add(attri);
        }
    }
    return list;
}
项目:alfresco-mt-support    文件:AuthenticationAndSynchronisationTests.java   
protected void createAndEnableTenant(final String tenantName)
{
    final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    final TenantAdminService tenantAdminService = context.getBean("TenantAdminService", TenantAdminService.class);

    if (!tenantAdminService.existsTenant(tenantName))
    {
        tenantAdminService.createTenant(tenantName, "admin".toCharArray());
        // eager sync requires "normal" enabling - won't on creation by design
        tenantAdminService.disableTenant(tenantName);
    }
    if (!tenantAdminService.isEnabledTenant(tenantName))
    {
        tenantAdminService.enableTenant(tenantName);
    }
}
项目:setaria    文件:WebConfigurerListener.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();

    // 初始化 Logback
    sc.setInitParameter(WebLogbackConfigurer.CONFIG_LOCATION_PARAM, findLogbackConfigLocation());
    WebLogbackConfigurer.initLogging(sc);

    // 初始化 Spring 配置
    sc.setInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "classpath:spring-setaria-console.xml");
    applicationContext = initWebApplicationContext(sc);

    // 注册 Spring Character Encoding
    registerCharacterEncoding(sc);

    // 注册 Spring Servlet
    registerDispatcherServlet(sc);

    // 注册 Spring FreeMarker Servlet 处理 FTL 请求
    registerSpringFreeMarkerServlet(sc);
}
项目:micro-server    文件:BootFrontEndApplicationConfigurator.java   
@Override
public void onStartup(ServletContext webappContext) throws ServletException {

    ModuleDataExtractor extractor = new ModuleDataExtractor(module);
    environment.assureModule(module);
    String fullRestResource = "/" + module.getContext() + "/*";

    ServerData serverData = new ServerData(environment.getModuleBean(module).getPort(), 
            Arrays.asList(),
            rootContext, fullRestResource, module);
    List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
    List<ServletData> servletDataList = extractor.createServletDataList(serverData);
    new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);

    new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
    PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
    PersistentList<ServletRequestListener> servletRequestListenerData = LinkedListX.fromIterable(module.getRequestListeners(serverData));

    new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);

}
项目:blcdemo    文件:MergeContextLoader.java   
/**
 * Instantiate the rootId WebApplicationContext for this loader, either the
 * default context class or a custom context class if specified.
 * <p>This implementation expects custom contexts to implement the
 * {@link ConfigurableWebApplicationContext} interface.
 * Can be overridden in subclasses.
 * <p>In addition, {@link #customizeContext} gets called prior to refreshing the
 * context, allowing subclasses to perform custom modifications to the context.
 * @param servletContext current servlet context
 * @param parent the parent ApplicationContext to use, or <code>null</code> if none
 * @return the rootId WebApplicationContext
 * @throws BeansException if the context couldn't be initialized
 * @see ConfigurableWebApplicationContext
 */
@Override
@Deprecated
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext, ApplicationContext parent) throws BeansException {
    MergeXmlWebApplicationContext wac = new MergeXmlWebApplicationContext();
    wac.setParent(parent);
    wac.setServletContext(servletContext);
    wac.setConfigLocation(servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM));
    wac.setPatchLocation(servletContext.getInitParameter(PATCH_LOCATION_PARAM));
    wac.setShutdownBean(servletContext.getInitParameter(SHUTDOWN_HOOK_BEAN));
    wac.setShutdownMethod(servletContext.getInitParameter(SHUTDOWN_HOOK_METHOD));
    customizeContext(servletContext, wac);
    wac.refresh();

    return wac;
}
项目:cosmo    文件:SpringContextInitializerListener.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    try {
        AbstractRefreshableWebApplicationContext wac = (AbstractRefreshableWebApplicationContext) WebApplicationContextUtils
                .getWebApplicationContext(sce.getServletContext());
        if (wac == null) {
            contextLoader = new ContextLoader();
            createSpringApplicationContext(sce.getServletContext());
        } else {
            WebApplicationContextHolder.set(wac);
            enhanceExistingSpringWebApplicationContext(sce, wac);
        }
    } catch (Exception t) {
        LOGGER.error("Exception occured", t);
    }
}
项目:class-guard    文件:SpringBeanAutowiringSupport.java   
/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 */
public static void processInjectionBasedOnCurrentContext(Object target) {
    Assert.notNull(target, "Target object must not be null");
    WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
    if (cc != null) {
        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
        bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
        bpp.processInjection(target);
    }
    else {
        if (logger.isDebugEnabled()) {
            logger.debug("Current WebApplicationContext is not available for processing of " +
                    ClassUtils.getShortName(target.getClass()) + ": " +
                    "Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
        }
    }
}
项目:class-guard    文件:Spr8510Tests.java   
/**
 * If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
 * then it should take precedence. This is generally not a recommended practice, but
 * when it does happen, the init-param should be considered more specific than the
 * programmatic configuration, given that it still quite possibly externalized in
 * hybrid web.xml + WebApplicationInitializer cases.
 */
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocation("programmatic.xml");
    ContextLoaderListener cll = new ContextLoaderListener(ctx);

    MockServletContext sc = new MockServletContext();
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

    try {
        cll.contextInitialized(new ServletContextEvent(sc));
        fail("expected exception");
    } catch (Throwable t) {
        // assert that an attempt was made to load the correct XML
        assertTrue(t.getMessage(), t.getMessage().endsWith(
                "Could not open ServletContext resource [/from-init-param.xml]"));
    }
}
项目:class-guard    文件:Spr8510Tests.java   
/**
 * If setConfigLocation has not been called explicitly against the application context,
 * then fall back to the ContextLoaderListener init-param if present.
 */
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
    ContextLoaderListener cll = new ContextLoaderListener(ctx);

    MockServletContext sc = new MockServletContext();
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

    try {
        cll.contextInitialized(new ServletContextEvent(sc));
        fail("expected exception");
    } catch (Throwable t) {
        // assert that an attempt was made to load the correct XML
        assertTrue(t.getMessage().endsWith(
                "Could not open ServletContext resource [/from-init-param.xml]"));
    }
}
项目:class-guard    文件:Spr8510Tests.java   
/**
 * Ensure that any custom default locations are still respected.
 */
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
    XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
        @Override
        protected String[] getDefaultConfigLocations() {
            return new String[] { "/WEB-INF/custom.xml" };
        }
    };
    //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
    ContextLoaderListener cll = new ContextLoaderListener(ctx);

    MockServletContext sc = new MockServletContext();
    sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");

    try {
        cll.contextInitialized(new ServletContextEvent(sc));
        fail("expected exception");
    } catch (Throwable t) {
        // assert that an attempt was made to load the correct XML
        System.out.println(t.getMessage());
        assertTrue(t.getMessage().endsWith(
                "Could not open ServletContext resource [/from-init-param.xml]"));
    }
}
项目:fastser-web    文件:RestHandlerMethodAdapter.java   
@Override
public Object handle(RestRequest request, RestResponse response, RestHandlerMethod handlerMethod) throws Exception {
    if(StringUtils.isNotEmpty(handlerMethod.getTable())){
        request.setTable(handlerMethod.getTable());
    }
    Object bean = ContextLoader.getCurrentWebApplicationContext().getBean(handlerMethod.getBeanName());

    Method method = ReflectionUtils.findMethod(bean.getClass(), handlerMethod.getMethodName(), type1);
    Object[] params = new Object[]{request, response};

    if(null == method){
        method = ReflectionUtils.findMethod(bean.getClass(), handlerMethod.getMethodName(), type2);
        params = new Object[]{response, request};
    }
    Object result = null;

    if(null != method.getReturnType()){
        result = ReflectionUtils.invokeMethod(method, bean, params);
    }else{
        ReflectionUtils.invokeMethod(method, bean, new Object[]{request, response});
    }

    return result;
}
项目:fastser-web    文件:RestHandlerValidatorAdapter.java   
@Override
public Object handle(RestRequest request, RestResponse response, RestHandlerMethod handlerMethod) throws Exception {
    if(StringUtils.isNotEmpty(handlerMethod.getTable())){
        request.setTable(handlerMethod.getTable());
    }
    Object bean = ContextLoader.getCurrentWebApplicationContext().getBean(handlerMethod.getBeanName());

    Method method = ReflectionUtils.findMethod(bean.getClass(), handlerMethod.getMethodName(), type1);
    Object[] params = new Object[]{request, response};

    if(null == method){
        method = ReflectionUtils.findMethod(bean.getClass(), handlerMethod.getMethodName(), type2);
        params = new Object[]{response, request};
    }
    Object result = null;

    if(null != method.getReturnType()){
        result = ReflectionUtils.invokeMethod(method, bean, params);
    }else{
        ReflectionUtils.invokeMethod(method, bean, new Object[]{request, response});
    }

    return result;
}
项目:spring-restlet    文件:RestletSpringApplicationContextServlet.java   
@SuppressWarnings("unchecked")
protected <T> T registerComponent(T bean, String name) {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ContextLoader.getCurrentWebApplicationContext()
            .getAutowireCapableBeanFactory();
    Class<T> clazz = (Class<T>) bean.getClass();
    String className = clazz.getCanonicalName();
    BeanDefinition beanDefinition = null;
    try {
        beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, className, clazz.getClassLoader());
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
    beanDefinition.setAutowireCandidate(true);

    beanFactory.registerBeanDefinition(name, beanDefinition);
    beanFactory.registerSingleton(name, bean);

    beanFactory.configureBean(bean, name);

    return bean;
}
项目:solo-spring    文件:AbstractPlugin.java   
/**
 * Initializes template engine configuration.
 */
private void initTemplateEngineCfg() {
    configuration = new Configuration();
    configuration.setDefaultEncoding("UTF-8");
    final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

    configuration.setServletContextForTemplateLoading(servletContext, "/plugins/" + dirName);
    logger.debug("Initialized template configuration:{}", dirName);
    readLangs();
}
项目:solo-spring    文件:Skins.java   
/**
 * Sets the directory for template loading with the specified skin directory
 * name, and sets the directory for mobile request template loading.
 *
 * @param skinDirName
 *            the specified skin directory name
 */
public static void setDirectoryForTemplateLoading(final String skinDirName) {
    final ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

    Templates.MAIN_CFG.setServletContextForTemplateLoading(servletContext, "/skins/" + skinDirName);
    Templates.MAIN_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    Templates.MAIN_CFG.setLogTemplateExceptions(false);

    Templates.MOBILE_CFG.setServletContextForTemplateLoading(servletContext, "/skins/mobile");
    Templates.MOBILE_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    Templates.MOBILE_CFG.setLogTemplateExceptions(false);
}
项目:automat    文件:SysServerListener.java   
public void contextInitialized(ServletContextEvent contextEvent) {
    WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    context.getBean(SysCacheService.class).flush();
    context.getBean(SysUserService.class).init();
    SysDicService sysDicService = context.getBean(SysDicService.class);
    sysDicService.getAllDic();
    super.contextInitialized(contextEvent);
}
项目:iBase4J    文件:JedisTemplate.java   
private static ShardedJedis getJedis() {
    if (shardedJedisPool == null) {
        synchronized (EXPIRE) {
            if (shardedJedisPool == null) {
                WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
                shardedJedisPool = wac.getBean(ShardedJedisPool.class);
            }
        }
    }
    return shardedJedisPool.getResource();
}
项目:iBase4J    文件:RedisHelper.java   
@SuppressWarnings("unchecked")
private RedisTemplate<Serializable, Serializable> getRedis() {
    if (redisTemplate == null) {
        synchronized (RedisHelper.class) {
            if (redisTemplate == null) {
                WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
                redisTemplate = (RedisTemplate<Serializable, Serializable>) wac.getBean("redisTemplate");
            }
        }
    }
    return redisTemplate;
}
项目:iBase4J    文件:RedissonHelper.java   
private RedissonClient getRedis() {
    if (redisTemplate == null) {
        synchronized (RedissonHelper.class) {
            if (redisTemplate == null) {
                WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
                redisTemplate = wac.getBean(Redisson.class);
            }
        }
    }
    return redisTemplate;
}
项目:JAVA-    文件:SysServerListener.java   
public void contextInitialized(ServletContextEvent contextEvent) {
    WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    context.getBean(SysCacheService.class).flush();
    context.getBean(SysUserService.class).init();
    SysDicService sysDicService = context.getBean(SysDicService.class);
    sysDicService.getAllDic();
    MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
    super.contextInitialized(contextEvent);
}
项目:spring-seed    文件:CommonWebInitializer.java   
private ApplicationContext loadRootApplicationContext(ServletContext servletContext, Class<?>... configClasses) {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.setAllowBeanDefinitionOverriding(true);
    rootContext.register(configClasses);

    servletContext.addListener(new ContextLoaderListener(rootContext));

    servletContext.setInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, APPLICATION_CONTEXT_INITIALIZER_CLASS.getName());

    return rootContext;
}
项目:spring4-understanding    文件:RedirectViewTests.java   
@Test
public void updateTargetUrlWithContextLoader() throws Exception {
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);

    MockServletContext servletContext = new MockServletContext();
    ContextLoader contextLoader = new ContextLoader(wac);
    contextLoader.initWebApplicationContext(servletContext);

    try {
        RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
        wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);

        RedirectView rv = new RedirectView();
        rv.setUrl("/path");

        MockHttpServletRequest request = createRequest();
        HttpServletResponse response = new MockHttpServletResponse();

        given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");

        rv.render(new ModelMap(), request, response);

        verify(mockProcessor).processUrl(request, "/path");
    }
    finally {
        contextLoader.closeWebApplicationContext(servletContext);
    }
}
项目:spring4-understanding    文件:DispatcherServletTests.java   
@Test
public void globalInitializerClasses() throws Exception {
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.setContextClass(SimpleWebApplicationContext.class);
    getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
            TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName());
    servlet.init(servletConfig);
    assertEquals("true", getServletContext().getAttribute("initialized"));
    assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
项目:spring4-understanding    文件:DispatcherServletTests.java   
@Test
public void mixedInitializerClasses() throws Exception {
    DispatcherServlet servlet = new DispatcherServlet();
    servlet.setContextClass(SimpleWebApplicationContext.class);
    getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
            TestWebContextInitializer.class.getName());
    servlet.setContextInitializerClasses(OtherWebContextInitializer.class.getName());
    servlet.init(servletConfig);
    assertEquals("true", getServletContext().getAttribute("initialized"));
    assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
项目:spring4-understanding    文件:SpringConfiguratorTests.java   
@Before
public void setup() {
    this.servletContext = new MockServletContext();

    this.webAppContext = new AnnotationConfigWebApplicationContext();
    this.webAppContext.register(Config.class);

    this.contextLoader = new ContextLoader(this.webAppContext);
    this.contextLoader.initWebApplicationContext(this.servletContext);

    this.configurator = new SpringConfigurator();
}
项目:spring4-understanding    文件:ContextLoaderTestUtils.java   
@SuppressWarnings("unchecked")
private static Map<ClassLoader, WebApplicationContext> getCurrentContextPerThreadFromContextLoader() {
    try {
        Field field = ContextLoader.class.getDeclaredField("currentContextPerThread");
        field.setAccessible(true);
        return (Map<ClassLoader, WebApplicationContext>) field.get(null);
    }
    catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}
项目:spring4-understanding    文件:SpringWebConstraintValidatorFactory.java   
/**
 * Retrieve the Spring {@link WebApplicationContext} to use.
 * The default implementation returns the current {@link WebApplicationContext}
 * as registered for the thread context class loader.
 * @return the current WebApplicationContext (never {@code null})
 * @see ContextLoader#getCurrentWebApplicationContext()
 */
protected WebApplicationContext getWebApplicationContext() {
    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    if (wac == null) {
        throw new IllegalStateException("No WebApplicationContext registered for current thread - " +
                "consider overriding SpringWebConstraintValidatorFactory.getWebApplicationContext()");
    }
    return wac;
}
项目:leopard    文件:FtlView.java   
public FtlView(String folder, String viewName) {
    try {
        ApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
        this.setApplicationContext(applicationContext);
    }
    catch (Exception e) {
        // 兼容普通java环境
    }
    this.setUrl(viewName + ".ftl");
    this.folder = folder;
}
项目:beyondj    文件:TypeConverterFactory.java   
@SuppressWarnings("rawtypes")
@Override

public TypeConverter getInstance(Class<? extends TypeConverter> clazz,
        Locale locale) throws Exception {
    TypeConverter converter = super.getInstance(clazz, locale);
    SpringHelper.injectBeans(converter,
            ContextLoader.getCurrentWebApplicationContext());
    return converter;
}
项目:OSCAR-ConCert    文件:OscarSpringContextLoaderListener.java   
@Override
   protected ContextLoader createContextLoader() {
    try {
        logger.info("Creating OscarContextLoader");
        return new OscarSpringContextLoader();
    } catch (Exception t) {
        logger.error("Unexpected error.", t);
        throw (new RuntimeException(t));
    }
}