本文整理汇总了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);
}
}