本文整理匯總了Java中org.springframework.web.context.ContextLoader類的典型用法代碼示例。如果您正苦於以下問題:Java ContextLoader類的具體用法?Java ContextLoader怎麽用?Java ContextLoader使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ContextLoader類屬於org.springframework.web.context包,在下文中一共展示了ContextLoader類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: readLangs
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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);
}
}
}
}
示例2: getSkinDirNames
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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;
}
示例3: processInjectionBasedOnCurrentContext
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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.");
}
}
}
示例4: abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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]"));
}
}
示例5: abstractRefreshableWAC_fallsBackToInitParam
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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]"));
}
}
示例6: customAbstractRefreshableWAC_fallsBackToInitParam
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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]"));
}
}
示例7: destroyMqConsumer
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 銷毀一個消費端
*
* 該方法 會通過傳遞的 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 + " 未找到 該消費者 ");
}
示例8: queryMqConsumerList
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 獲取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;
}
示例9: loginOnDemandSynchTenantAlpha
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
@Test
public void loginOnDemandSynchTenantAlpha()
{
AuthenticationUtil.setFullyAuthenticatedUser("admin");
this.createAndEnableTenant("tenantalpha");
final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
final PersonService personService = context.getBean("PersonService", PersonService.class);
TenantUtil.runAsTenant(() -> {
Assert.assertFalse("User [email protected] should not have been synchronized yet",
personService.personExists("[email protected]"));
return null;
}, "tenantalpha");
AuthenticationUtil.clearCurrentSecurityContext();
final AuthenticationService authenticationService = context.getBean("AuthenticationService", AuthenticationService.class);
authenticationService.authenticate("[email protected]", "afaust".toCharArray());
this.checkUserExistsAndState("[email protected]", "Axel", "Faust", false);
}
示例10: loginNoSyncTenantBeta
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
@Test
public void loginNoSyncTenantBeta()
{
AuthenticationUtil.setFullyAuthenticatedUser("admin");
this.createAndEnableTenant("tenantbeta");
final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
final PersonService personService = context.getBean("PersonService", PersonService.class);
TenantUtil.runAsTenant(() -> {
Assert.assertFalse("User [email protected] should not have been created yet", personService.personExists("[email protected]"));
return null;
}, "tenantbeta");
AuthenticationUtil.clearCurrentSecurityContext();
final AuthenticationService authenticationService = context.getBean("AuthenticationService", AuthenticationService.class);
authenticationService.authenticate("[email protected]", "afaust".toCharArray());
this.checkUserExistsAndState("[email protected]", "afaust", "", false);
Assert.assertFalse("User [email protected] should not have been eagerly synchronized",
personService.personExists("[email protected]"));
}
示例11: createAndEnableTenant
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
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);
}
}
示例12: contextInitialized
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
@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);
}
示例13: onStartup
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
@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);
}
示例14: createWebApplicationContext
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
/**
* 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;
}
示例15: contextInitialized
import org.springframework.web.context.ContextLoader; //導入依賴的package包/類
@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);
}
}