org.springframework.context.ApplicationContext类的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(15.5k)|赞(0)|评价(0)|浏览(158)

本文整理了Java中org.springframework.context.ApplicationContext类的一些代码示例,展示了ApplicationContext类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ApplicationContext类的具体详情如下:
包路径:org.springframework.context.ApplicationContext
类名称:ApplicationContext

ApplicationContext介绍

[英]Central interface to provide configuration for an application. This is read-only while the application is running, but may be reloaded if the implementation supports this.

An ApplicationContext provides:

  • Bean factory methods for accessing application components. Inherited from org.springframework.beans.factory.ListableBeanFactory.
  • The ability to load file resources in a generic fashion. Inherited from the org.springframework.core.io.ResourceLoader interface.
  • The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

In addition to standard org.springframework.beans.factory.BeanFactorylifecycle capabilities, ApplicationContext implementations detect and invoke ApplicationContextAware beans as well as ResourceLoaderAware, ApplicationEventPublisherAware and MessageSourceAware beans.
[中]为应用程序提供配置的中央接口。在应用程序运行时,这是只读的,但如果实现支持,则可能会重新加载。
ApplicationContext提供:
*用于访问应用程序组件的Bean工厂方法。继承自组织。springframework。豆。工厂ListableBeanFactory。
*以通用方式加载文件资源的能力。继承自组织。springframework。果心木卫一。ResourceLoader接口。
*将事件发布到已注册侦听器的功能。从ApplicationEventPublisher接口继承。
*能够解析消息,支持国际化。从MessageSource接口继承。
*从父上下文继承。子体上下文中的定义将始终优先。例如,这意味着整个web应用程序可以使用单个父上下文,而每个servlet都有自己的子上下文,独立于任何其他servlet的子上下文。
除了标准组织。springframework。豆。工厂BeanFactorylifecycle功能、ApplicationContext实现检测并调用ApplicationContextAware bean以及ResourceLoaderware、ApplicationEventPublisherAware和MessageSourceAware bean。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test
public void staticScriptWithNullReturnValue() {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass());
  assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfig"));
  ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerWithConfig");
  messenger.setMessage(null);
  assertNull(messenger.getMessage());
  assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger));
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public void afterPropertiesSet() throws Exception {
  if (dubboConfigBinder == null) {
    try {
      dubboConfigBinder = applicationContext.getBean(DubboConfigBinder.class);
    } catch (BeansException ignored) {
      if (log.isDebugEnabled()) {
        log.debug("DubboConfigBinder Bean can't be found in ApplicationContext.");
      }
      // Use Default implementation
      dubboConfigBinder = createDubboConfigBinder(applicationContext.getEnvironment());
    }
  }
  dubboConfigBinder.setIgnoreUnknownFields(ignoreUnknownFields);
  dubboConfigBinder.setIgnoreInvalidFields(ignoreInvalidFields);
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Create a default strategy.
 * <p>The default implementation uses
 * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
 * @param context the current WebApplicationContext
 * @param clazz the strategy implementation class to instantiate
 * @return the fully configured strategy instance
 * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
 * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean
 */
protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {
  return context.getAutowireCapableBeanFactory().createBean(clazz);
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Return the {@link RequestDataValueProcessor} to use.
 * <p>The default implementation looks in the {@link #getApplicationContext()
 * Spring configuration} for a {@code RequestDataValueProcessor} bean with
 * the name {@link #REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME}.
 * @return the RequestDataValueProcessor, or null if there is none at the
 * application context.
 */
@Nullable
protected RequestDataValueProcessor getRequestDataValueProcessor() {
  ApplicationContext context = getApplicationContext();
  if (context != null && context.containsBean(REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
    return context.getBean(REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
  }
  return null;
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public View resolveViewName(String viewName, Locale locale) throws BeansException {
  ApplicationContext context = obtainApplicationContext();
  if (!context.containsBean(viewName)) {
    // Allow for ViewResolver chaining...
    return null;
  }
  if (!context.isTypeMatch(viewName, View.class)) {
    if (logger.isDebugEnabled()) {
      logger.debug("Found bean named '" + viewName + "' but it does not implement View");
    }
    // Since we're looking into the general ApplicationContext here,
    // let's accept this as a non-match and allow for chaining as well...
    return null;
  }
  return context.getBean(viewName, View.class);
}

代码示例来源:origin: org.pustefixframework/pustefix-core

@Override
public void execute(HttpServletRequest req, HttpServletResponse res, PageContext pageContext) throws IOException {
  SessionAdmin sessionAdmin = pageContext.getApplicationContext().getBean(SessionAdmin.class);
          Socket sock = new Socket("localhost", port);
          OutputStream out = sock.getOutputStream();
          PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
          writer.println("reload");
          writer.println(workDir.getPath());
          writer.close();
        } else {
    LOG.warn("Skipped repeated webapp reload scheduling.");
  String page = req.getParameter("page");
  if(page == null) {
    res.sendRedirect(req.getContextPath() + "/pfxinternals/actions");
  } else {
    sendReloadPage(req, res);

代码示例来源:origin: org.pustefixframework/pustefix-core

LOGGER.debug("*** Setting custom supplied header: " + key + " -> " + val);
    res.setHeader(key, val);
  res.setDateHeader("Expires", System.currentTimeMillis() + maxAge);
  res.setHeader("Cache-Control", "max-age=" + maxAge / 1000 +", private");
} else {
  String reqId = preq.getRequest().getHeader("Request-Id");
  if(reqId != null) {
    res.addHeader("Request-Id", reqId);
        PustefixHandlerMapping handlerMapping = (PustefixHandlerMapping)applicationContext.getBean(PustefixHandlerMapping.class.getName());
        handlerMapping.reload();
preq.getRequest().setAttribute(TRAFOTIME, handletime);

代码示例来源:origin: org.apache.cxf.fediz/fediz-idp-core

ConfigService cs = (ConfigService)getApplicationContext().getBean("config");
Idp idpConfig = cs.getIDP(realm);
try {
  boolean isSamlRequest = request.getQueryString() != null
    && request.getQueryString().contains("protocol=saml");
  if (request.getServletPath() != null && request.getServletPath().startsWith("/metadata")) {
    String parsedRealm =
      request.getRequestURI().substring(request.getRequestURI().indexOf("/metadata")
      IdpMetadataWriter mw = new IdpMetadataWriter();
      Document metadata = mw.getMetaData(idpConfig, isSamlRequest);
      out.write(DOM2Writer.nodeToString(metadata));
      return;
    if (trustedIdp == null) {
      LOG.error("No TrustedIdp found for desired realm: " + parsedRealm);
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    out.write(DOM2Writer.nodeToString(metadata));
  } else {
    IdpMetadataWriter mw = new IdpMetadataWriter();
    Document metadata = mw.getMetaData(idpConfig, isSamlRequest);
    out.write(DOM2Writer.nodeToString(metadata));

代码示例来源:origin: cn-cerc/summer-mis

HttpServletResponse resp = (HttpServletResponse) response;
String uri = req.getRequestURI();
Application.get(req);
  if (req.getParameter(ClientDevice.deviceId_key) != null)
    req.getSession().setAttribute(ClientDevice.deviceId_key, req.getParameter(ClientDevice.deviceId_key));
  if (req.getParameter(ClientDevice.deviceType_key) != null)
    req.getSession().setAttribute(ClientDevice.deviceType_key,
  resp.sendRedirect(String.format("/%s/%s", conf.getPathForms(), conf.getFormWelcome()));
  return;
} else if (uri.equals("/MobileConfig") || uri.equals("/mobileConfig")) {
  try {
    IForm form;
    if (Application.get(req).containsBean("mobileConfig"))
      form = Application.getBean("mobileConfig", IForm.class);
    else
    page.execute();
  } catch (Exception e) {
    resp.getWriter().print(e.getMessage());

代码示例来源:origin: yuboon/Aooms

@Override
  public void finalHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    Record record = (Record) request.getAttribute(DB_LOGGER);
    if(record != null){
      DbLogService dbLogService = (DbLogService)SpringUtils.getApplicationContext().getBean("dbLogService");
      if(ex != null){
        StringWriter stackTrace = new StringWriter();
        ex.printStackTrace(new PrintWriter(stackTrace));
        stackTrace.flush();
        record.set("status", "1");
        record.set("trace", stackTrace.toString());
      }

      long start = record.getLong("cost");
      record.set("cost", (System.currentTimeMillis() - start) / 1000); // 单位:s
      dbLogService.saveLog(record);
    }
  }
}

代码示例来源:origin: org.pustefixframework/pustefix-core

@Override
public void execute(HttpServletRequest req, HttpServletResponse res, PageContext pageContext) throws IOException {
  
  TargetGenerator targetGenerator = pageContext.getApplicationContext().getBean(TargetGenerator.class);
  try {
    targetGenerator.forceReinit();
    LOG.info("Reloaded TargetGenerator with cleared cache.");
  } catch (Exception e) {
    LOG.error("Error while clearing TargetGenerator cache", e);
  }
  String referer = req.getHeader("Referer");
  if(referer != null && !referer.contains("pfxinternals")) {
    res.sendRedirect(referer);
    return;
  } else {
    res.sendRedirect(req.getContextPath()+ "/pfxinternals/actions");
    return;
  }
  
}

代码示例来源:origin: cn-cerc/summer-mis

@RequestMapping("/{formId}.{funcId}")
public String execute(@PathVariable String formId, @PathVariable String funcId) {
  log.debug(String.format("formId: %s, funcId: %s", formId, funcId));
  if (!context.containsBean(formId))
    return String.format("formId: %s, funcId: %s", formId, funcId);
  IForm form = context.getBean(formId, IForm.class);
  try {
    form.setHandle(handle);
    handle.setProperty(Application.sessionId, request.getSession().getId());
    handle.setProperty(Application.deviceLanguage, clientDevice.getLanguage());
    request.setAttribute("myappHandle", handle);
    request.setAttribute("_showMenu_", !ClientDevice.device_ee.equals(clientDevice.getDevice()));
      response.setContentType("application/vnd.ms-excel; charset=UTF-8");
      response.addHeader("Content-Disposition", "attachment; filename=excel.csv");
    } else
      response.setContentType("text/html;charset=UTF-8");

代码示例来源:origin: org.pustefixframework/pustefix-core

@Override
public void execute(HttpServletRequest req, HttpServletResponse res, PageContext pageContext) throws IOException {
  
  SessionAdmin sessionAdmin = pageContext.getApplicationContext().getBean(SessionAdmin.class);
  
  String session = req.getParameter("session");
  String page = req.getParameter("page");
  if(session == null) {
    sessionAdmin.invalidateSessions();
    LOG.info("Invalidated sessions.");
  } else {
    sessionAdmin.invalidateSession(session);
    LOG.info("Invalidated session: " + session);
  }
  if(page == null) {
    res.sendRedirect(req.getContextPath()+ "/pfxinternals/actions");
  } else {
    String url = req.getRequestURI();
    url = url.replace("pfxinternals", req.getParameter("page"));
    res.sendRedirect(url.toString());
  }
  
}

代码示例来源:origin: pebbleblog/pebble

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
BloggerAPIHandler bloggerApi = (BloggerAPIHandler)ctx.getBean("bloggerApiHandler");
xmlrpc.addHandler("blogger", bloggerApi);
MetaWeblogAPIHandler metaweblogApi = (MetaWeblogAPIHandler)ctx.getBean("metaweblogApiHandler");
xmlrpc.addHandler("metaWeblog", metaweblogApi);
PebbleAPIHandler pebbleApi = (PebbleAPIHandler)ctx.getBean("pebbleApiHandler");
xmlrpc.addHandler("pebble", pebbleApi);
SearchAPIHandler searchApi = (SearchAPIHandler)ctx.getBean("searchApiHandler");
xmlrpc.addHandler("search", searchApi);
byte[] result = xmlrpc.execute(request.getInputStream());
response.setContentType("text/xml; charset=UTF-8");
response.setContentLength(result.length);
OutputStream out = response.getOutputStream();
out.write(result);
out.flush();

代码示例来源:origin: psi-probe/psi-probe

seriesColor[0] = Utils.toIntHex(request.getParameter("s1c"), 0x9bd2fb);
seriesColor[1] = Utils.toIntHex(request.getParameter("s2c"), 0xFF0606);
for (int i = 2; i < seriesMaxCount; i++) {
 seriesColor[i] = Utils.toIntHex(request.getParameter("s" + (i + 1) + "c"), -1);
 Object series = getApplicationContext().getBean(provider);
 if (series instanceof SeriesProvider) {
  ((SeriesProvider) series).populate(ds, statsCollection, request);
 chart.getXYPlot().setInsets(new RectangleInsets(-15, 0, 0, 10));
 response.setHeader("Content-type", "image/png");
 response.getOutputStream()
   .write(ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height)));

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

String fullUrl = removeAssetPrefix(request.getRequestURI());
context.setNonPersistentSite(siteResolver.resolveSite(new ServletWebRequest(request, response)));
try {
  Map<String, String> model = staticAssetStorageService.getCacheFileModel(fullUrl, convertParameterMap(request.getParameterMap()));
  View assetView = appCtx.getBean(viewResolverName, View.class);
  return new ModelAndView(assetView, model);
} catch (AssetNotFoundException e) {
  response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  return null;
} catch (FileNotFoundException e) {
  response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  LOG.error("Could not retrieve asset request " + fullUrl + " from the StaticAssetStorage. The underlying file path checked was " + e.getMessage());
  return null;

代码示例来源:origin: org.springframework.extensions.surf/spring-surf

deployedModules.add(createModuleDefinition(deployedModule).toString());
undeployedModules.add(createModuleDefinition(undeployedModule).toString());
JSONObject defaultEvaluator = new JSONObject();
defaultEvaluator.put("id", "");
JSONArray defaultEvaluatorReqProps = new JSONArray();
Map<String, ExtensionModuleEvaluator> evaluatorMap = this.applicationContext.getBeansOfType(ExtensionModuleEvaluator.class);
for (Entry<String, ExtensionModuleEvaluator> evaluatorEntry: evaluatorMap.entrySet())

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testWithTwoClassesDefinedInTheOneGroovyFile_WrongClassFirst() throws Exception {
  try {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass());
    ctx.getBean("messenger", Messenger.class);
    fail("Must have failed: two classes defined in GroovyScriptFactory source, non-Messenger class defined first.");
  }
  // just testing for failure here, hence catching Exception...
  catch (Exception expected) {
  }
}

代码示例来源:origin: org.alfresco/alfresco-repository

SolrAdminHTTPClient adminClient = (SolrAdminHTTPClient) ctx.getBean("search.solrAdminHTTPCLient");
HashMap<String, String> args = new HashMap<String, String>();
args.put("action", "SUMMARY");
args.put("wt", "json");
JSONObject json = adminClient.execute(args);
JSONObject summary = json.getJSONObject("Summary");
  alfresco = summary.getJSONObject("alfresco");
    String alfrescoActive = alfresco.getString("Active");
    if (alfrescoActive == null || alfrescoActive.isEmpty())

代码示例来源:origin: spring-projects/spring-batch-admin

request.getSession();
response.flushBuffer();
for (int i = 0; i < attrNames.length; i++) {
  View fragmentView = null;
    fragmentView = (View) getApplicationContext().getBean(attrNames[i], View.class);

相关文章