下面列出了怎么用org.springframework.context.support.FileSystemXmlApplicationContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void fileSystemXmlApplicationContext() throws IOException {
ClassPathResource xml = new ClassPathResource(XML_PATH);
File tmpFile = File.createTempFile("test", "xml");
FileCopyUtils.copy(xml.getFile(), tmpFile);
// strange - FSXAC strips leading '/' unless prefixed with 'file:'
ConfigurableApplicationContext ctx =
new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertEnvironmentBeanRegistered(ctx);
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
@Test
public void fileSystemXmlApplicationContext() throws IOException {
ClassPathResource xml = new ClassPathResource(XML_PATH);
File tmpFile = File.createTempFile("test", "xml");
FileCopyUtils.copy(xml.getFile(), tmpFile);
// strange - FSXAC strips leading '/' unless prefixed with 'file:'
ConfigurableApplicationContext ctx =
new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertEnvironmentBeanRegistered(ctx);
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
public static void main(String[] args) {
if (args.length == 0 || "".equals(args[0])) {
System.out.println(
"You need to specify an order ID and optionally a number of calls, e.g. for order ID 1000: " +
"'client 1000' for a single call per service or 'client 1000 10' for 10 calls each");
}
else {
int orderId = Integer.parseInt(args[0]);
int nrOfCalls = 1;
if (args.length > 1 && !"".equals(args[1])) {
nrOfCalls = Integer.parseInt(args[1]);
}
ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext(CLIENT_CONTEXT_CONFIG_LOCATION);
OrderServiceClient client = new OrderServiceClient(beanFactory);
client.invokeOrderServices(orderId, nrOfCalls);
}
}
public static void main(String[] args)
{
if (args.length != 2)
{
System.err.println("Usage:");
System.err.println("java " + DbToXML.class.getName() + " <context.xml> <output.xml>");
System.exit(1);
}
String contextPath = args[0];
File outputFile = new File(args[1]);
// Create the Spring context
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(contextPath);
DbToXML dbToXML = new DbToXML(context, outputFile);
dbToXML.execute();
// Shutdown the Spring context
context.close();
}
@Test
public void fileSystemXmlApplicationContext() throws IOException {
ClassPathResource xml = new ClassPathResource(XML_PATH);
File tmpFile = File.createTempFile("test", "xml");
FileCopyUtils.copy(xml.getFile(), tmpFile);
// strange - FSXAC strips leading '/' unless prefixed with 'file:'
ConfigurableApplicationContext ctx =
new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertEnvironmentBeanRegistered(ctx);
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
public static void main(String[] args) {
if (args.length == 0 || "".equals(args[0])) {
System.out.println(
"You need to specify an order ID and optionally a number of calls, e.g. for order ID 1000: " +
"'client 1000' for a single call per service or 'client 1000 10' for 10 calls each");
}
else {
int orderId = Integer.parseInt(args[0]);
int nrOfCalls = 1;
if (args.length > 1 && !"".equals(args[1])) {
nrOfCalls = Integer.parseInt(args[1]);
}
ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext(CLIENT_CONTEXT_CONFIG_LOCATION);
OrderServiceClient client = new OrderServiceClient(beanFactory);
client.invokeOrderServices(orderId, nrOfCalls);
}
}
public HapporSpringContext(final ClassLoader classLoader, String filename) {
this.classLoader = classLoader;
ctx = new FileSystemXmlApplicationContext(filename) {
@Override
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
super.initBeanDefinitionReader(reader);
reader.setBeanClassLoader(classLoader);
setClassLoader(classLoader);
}
};
registerAllBeans();
setServer(ctx.getBean(HapporWebserver.class));
try {
setWebserverHandler(ctx.getBean(WebserverHandler.class));
} catch (NoSuchBeanDefinitionException e) {
logger.warn("has no WebserverHandler");
}
}
public AbstractDaoTestCase(String testName) {
super(testName);
ApplicationContext springApplicationContext =
new FileSystemXmlApplicationContext(SPRING_FILE_PATH);
springBeanFactory = springApplicationContext;
DriverManagerDataSource dmds =
(DriverManagerDataSource)springBeanFactory.getBean("dataSource");
System.setProperty(
PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
JDBC_DRIVER);
System.setProperty(
PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
dmds.getUrl());
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
dmds.getUsername());
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
dmds.getPassword());
}
public AbstractDaoTestCase(String testName) {
super(testName);
ApplicationContext springApplicationContext =
new FileSystemXmlApplicationContext(SPRING_FILE_PATH);
springBeanFactory = springApplicationContext;
DriverManagerDataSource dmds =
(DriverManagerDataSource)springBeanFactory.getBean("dataSource");
System.setProperty(
PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
JDBC_DRIVER);
System.setProperty(
PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
dmds.getUrl());
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
dmds.getUsername());
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
dmds.getPassword());
}
/**
*
* @throws Exception If failed.
*/
private void startNodes() throws Exception {
AbstractApplicationContext ctxSpring = new FileSystemXmlApplicationContext(springCfgFileOutTmplName + 0);
// We have to deploy Services for service is available at the bean creation time for other nodes.
Ignite ignite = (Ignite)ctxSpring.getBean("testIgnite");
ignite.services().deployMultiple(SERVICE_NAME, new DummyServiceImpl(), NODES, 1);
// Add other nodes.
for (int i = 1; i < NODES; ++i)
new FileSystemXmlApplicationContext(springCfgFileOutTmplName + i);
assertEquals(NODES, G.allGrids().size());
assertEquals(NODES, ignite.cluster().nodes().size());
}
/**
* Validate spring client configuration.
*
* @throws Exception In case of any exception.
*/
@Test
public void testSpringConfig() throws Exception {
GridClientConfiguration cfg = new FileSystemXmlApplicationContext(
GRID_CLIENT_SPRING_CONFIG.toString()).getBean(GridClientConfiguration.class);
assertEquals(Arrays.asList("127.0.0.1:11211"), new ArrayList<>(cfg.getServers()));
assertNull(cfg.getSecurityCredentialsProvider());
Collection<GridClientDataConfiguration> dataCfgs = cfg.getDataConfigurations();
assertEquals(1, dataCfgs.size());
GridClientDataConfiguration dataCfg = dataCfgs.iterator().next();
assertEquals("partitioned", dataCfg.getName());
assertNotNull(dataCfg.getPinnedBalancer());
assertEquals(GridClientRandomBalancer.class, dataCfg.getPinnedBalancer().getClass());
assertNotNull(dataCfg.getAffinity());
assertEquals(GridClientPartitionAffinity.class, dataCfg.getAffinity().getClass());
}
@Before
public void startServer() throws IOException {
final String listName = NamedListWriter.FALLBACK_LIST_NAME;
this.recordListFilledByListWriter = NamedListWriter.createNamedList(listName);
// We must use System.setProperty (and not a new custom Configuration instance)
// because the probe for the spring intercepter uses the singleton instance of the monitoring controller
// which reads its properties by configuration file and system properties
System.setProperty(ConfigurationKeys.META_DATA, "false");
System.setProperty(ConfigurationKeys.HOST_NAME, HOSTNAME);
System.setProperty(ConfigurationKeys.CONTROLLER_NAME, CTRLNAME);
System.setProperty(ConfigurationKeys.WRITER_CLASSNAME, NamedListWriter.class.getName());
// Doesn't work because the property does not start with kieker.monitoring:
// System.setProperty(NamedListWriter.CONFIG_PROPERTY_NAME_LIST_NAME, listName);
// this.monitoringController = MonitoringController.getInstance();
// start the server
final URL configURL = TestSpringMethodInterceptor.class
.getResource("/kieker/test/monitoring/junit/probe/spring/executions/jetty/jetty.xml");
this.ctx = new FileSystemXmlApplicationContext(configURL.toExternalForm());
// Note that the Spring interceptor is configured in
// test/monitoring/kieker/test/monitoring/junit/probe/spring/executions/jetty/webapp/WEB-INF/spring/servlet-context.xml
// to only instrument
// Bookstore.searchBook and Catalog.getBook
}
@Before
public void startServer() throws IOException {
final String listName = NamedListWriter.FALLBACK_LIST_NAME;
this.recordListFilledByListWriter = NamedListWriter.createNamedList(listName);
// We must use System.setProperty (and not a new custom Configuration instance)
// because the probe for the spring intercepter uses the singleton instance of the monitoring controller
// which reads its properties by configuration file and system properties
System.setProperty(ConfigurationKeys.ADAPTIVE_MONITORING_ENABLED, "true");
System.setProperty(ConfigurationKeys.META_DATA, "false");
System.setProperty(ConfigurationKeys.HOST_NAME, HOSTNAME);
System.setProperty(ConfigurationKeys.CONTROLLER_NAME, CTRLNAME);
System.setProperty(ConfigurationKeys.WRITER_CLASSNAME, NamedListWriter.class.getName());
// Doesn't work because the property does not start with kieker.monitoring:
// System.setProperty(NamedListWriter.CONFIG_PROPERTY_NAME_LIST_NAME, listName);
// start the server
final URL configURL = TestSpringMethodInterceptor.class
.getResource("/kieker/test/monitoring/junit/probe/spring/executions/jetty/jetty.xml");
this.ctx = new FileSystemXmlApplicationContext(configURL.toExternalForm());
// Note that the Spring interceptor is configured in
// test/monitoring/kieker/test/monitoring/junit/probe/spring/executions/jetty/webapp/WEB-INF/spring/servlet-context.xml
// to only instrument
// Bookstore.searchBook and Catalog.getBook
// this.ctx.getBean(Bookstore.class).searchBook();
}
@Override
public void execute(ActionMessagePrinter printer)
throws CmdLineActionException {
FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext(
this.beanRepo);
try {
ProductCrawler pc = (ProductCrawler) appContext
.getBean(crawlerId != null ? crawlerId : getName());
pc.setApplicationContext(appContext);
if (pc.getDaemonPort() != -1 && pc.getDaemonWait() != -1) {
new CrawlDaemon(pc.getDaemonWait(), pc, pc.getDaemonPort())
.startCrawling();
printer.println("Finished crawler daemon");
} else {
pc.crawl();
printer.println("Finished crawling");
}
pc.shutdown();
} catch (Exception e) {
throw new CmdLineActionException("Failed to launch crawler : "
+ e.getMessage(), e);
}
}
public void testLoadAndValidateActions() {
ProductCrawler pc = createDummyCrawler();
pc.setApplicationContext(new FileSystemXmlApplicationContext(
CRAWLER_CONFIG));
pc.loadAndValidateActions();
assertEquals(0, pc.actionRepo.getActions().size());
pc = createDummyCrawler();
pc.setApplicationContext(new FileSystemXmlApplicationContext(
CRAWLER_CONFIG));
pc.setActionIds(Lists.newArrayList("Unique", "DeleteDataFile"));
pc.loadAndValidateActions();
assertEquals(Sets.newHashSet(
pc.getApplicationContext().getBean("Unique"),
pc.getApplicationContext().getBean("DeleteDataFile")),
pc.actionRepo.getActions());
}
public boolean start() {
if (ctx != null)
IocInterceptor.ctx = ctx;
else if (configurations != null)
IocInterceptor.ctx = new FileSystemXmlApplicationContext(configurations);
else
IocInterceptor.ctx = new FileSystemXmlApplicationContext(PathKit.getWebRootPath() + "/WEB-INF/applicationContext.xml");
return true;
}
public static void main(String args[]){
ApplicationContext context = new FileSystemXmlApplicationContext(".\\src\\main\\webapp\\WEB-INF\\applicationContext.xml");
//Calculation calculation = (Calculation)context.getBean("calculationBeanHessian");
InvoiceProductRequest request = new InvoiceProductRequest();
request.setInvoiceId(123);
WebServiceTemplate wsTemplate = (WebServiceTemplate) context.getBean("webServiceTemplate");
InvoiceProductResponse response = (InvoiceProductResponse) wsTemplate.marshalSendAndReceive(request);
InvoicedProducts product = response.getInvoicedProduct();
System.out.println(product.getId());
}
@Test
public void testFileSystemXmlApplicationContext() {
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:spring/spring-beans.xml");
Person person = ctx.getBean("person_zhangsan", Person.class);
Assert.assertNotNull(person);
System.out.println(person);
((FileSystemXmlApplicationContext) ctx).close();
}
@Test
public void testFileSystemXmlApplicationContext2() {
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:*/*.xml");
Person person = ctx.getBean("person_zhangsan", Person.class);
Assert.assertNotNull(person);
System.out.println(person);
((FileSystemXmlApplicationContext) ctx).close();
}
public static void main(String[] args) throws IOException {
int nrOfCalls = 1;
if (args.length > 1 && !"".equals(args[1])) {
nrOfCalls = Integer.parseInt(args[1]);
}
ApplicationContext context = new FileSystemXmlApplicationContext(CONTEXT_CONFIG_LOCATION);
ImageDatabase idb = (ImageDatabase) context.getBean("imageDatabase");
StandaloneImageTool tool = new StandaloneImageTool(idb);
tool.listImages(nrOfCalls);
}
public JarContainerServer(String filename) {
FileSystemXmlApplicationContext serverContext = new FileSystemXmlApplicationContext(filename);
HapporServerElement element = serverContext.getBean(HapporServerElement.class);
server = element.getServer();
containerConfig = element.getConfigs().get("container");
log4jConfig = element.getConfigs().get("log4j");
serverContext.close();
}
/**
*
* @param asqatasunHome
*/
private void initServices(String asqatasunHome) {
ApplicationContext springApplicationContext = new FileSystemXmlApplicationContext(asqatasunHome + "/" + APPLICATION_CONTEXT_FILE_PATH);
BeanFactory springBeanFactory = springApplicationContext;
auditService = (AuditService) springBeanFactory.getBean("auditService");
auditDataService = (AuditDataService) springBeanFactory.getBean("auditDataService");
webResourceDataService = (WebResourceDataService) springBeanFactory.getBean("webResourceDataService");
webResourceStatisticsDataService = (WebResourceStatisticsDataService) springBeanFactory.getBean("webResourceStatisticsDataService");
processResultDataService = (ProcessResultDataService) springBeanFactory.getBean("processResultDataService");
processRemarkDataService = (ProcessRemarkDataService) springBeanFactory.getBean("processRemarkDataService");
parameterDataService = (ParameterDataService) springBeanFactory.getBean("parameterDataService");
parameterElementDataService = (ParameterElementDataService) springBeanFactory.getBean("parameterElementDataService");
auditService.add(this);
}
@Override
protected void beforeRun(Outline outline, Options options) throws Exception {
super.beforeRun(outline, options);
final String[] configLocations = getConfigLocations();
if (!ArrayUtils.isEmpty(configLocations)) {
final String configLocationsString = ArrayUtils
.toString(configLocations);
logger.debug("Loading application context from ["
+ configLocationsString + "].");
try {
applicationContext = new FileSystemXmlApplicationContext(
configLocations, false);
applicationContext.setClassLoader(Thread.currentThread()
.getContextClassLoader());
applicationContext.refresh();
if (getAutowireMode() != AutowireCapableBeanFactory.AUTOWIRE_NO) {
applicationContext.getBeanFactory().autowireBeanProperties(
this, getAutowireMode(), isDependencyCheck());
}
} catch (Exception ex) {
ex.printStackTrace();
ex.getCause().printStackTrace();
logger.error("Error loading applicaion context from ["
+ configLocationsString + "].", ex);
throw new BadCommandLineException(
"Error loading applicaion context from ["
+ configLocationsString + "].", ex);
}
}
}
@Before
public void IntiRes() {
DOMConfigurator.configure("res/appConfig/log4j.xml");
System.setProperty("java.net.preferIPv4Stack", "true"); //Disable IPv6 in JVM
springContext = new FileSystemXmlApplicationContext("res/springConfig/spring-context.xml");
/**初始化spring容器*/
testPubSub = (TestPubSub) springContext.getBean("testPubSub");
}
private void createSpringContext(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
if(request.getParameter("filePath") == null) {
} else {
springContextPath = request.getParameter("filePath").toString();
}
ServletContext application = this.getServletConfig().getServletContext();
ApplicationContext context = new FileSystemXmlApplicationContext("file:" + springContextPath);
application.setAttribute("springContext", context);
session.setAttribute("springContextData", context.toString());
response.sendRedirect("sql.jsp");
}
/**
* Unloads a context (Red5 application) and removes it from the context map, then removes it's beans from the parent (that is, Red5)
*
* @param name
* Context name
*/
public void unloadContext(String name) {
log.debug("Un-load context - name: {}", name);
ApplicationContext context = contextMap.remove(name);
log.debug("Context from map: {}", context);
String[] bnames = BeanFactoryUtils.beanNamesIncludingAncestors(context);
for (String bname : bnames) {
log.debug("Bean: {}", bname);
}
ConfigurableBeanFactory factory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
if (factory.containsSingleton(name)) {
log.debug("Context found in parent, destroying: {}", name);
FileSystemXmlApplicationContext ctx = (FileSystemXmlApplicationContext) factory.getSingleton(name);
if (ctx.isRunning()) {
log.debug("Context was running, attempting to stop");
ctx.stop();
}
if (ctx.isActive()) {
log.debug("Context is active, attempting to close");
ctx.close();
} else {
try {
factory.destroyBean(name, ctx);
} catch (Exception e) {
log.warn("Context destroy failed for: {}", name, e);
} finally {
if (factory.containsSingleton(name)) {
log.debug("Singleton still exists, trying another destroy method");
((DefaultListableBeanFactory) factory).destroySingleton(name);
}
}
}
} else {
log.debug("Context does not contain singleton: {}", name);
}
context = null;
}
protected ProductCrawler createProductCrawler()
throws MalformedURLException, IllegalAccessException, CrawlerActionException, MetExtractionException,
InstantiationException, FileNotFoundException, ClassNotFoundException {
/* create a ProductCrawler based on whether or not the output dir specifies a MIME_EXTRACTOR_REPO */
logger.info("Configuring ProductCrawler...");
ProductCrawler crawler;
if (pgeMetadata.getMetadata(MIME_EXTRACTOR_REPO) != null &&
!pgeMetadata.getMetadata(MIME_EXTRACTOR_REPO).equals("")) {
crawler = new AutoDetectProductCrawler();
((AutoDetectProductCrawler) crawler).
setMimeExtractorRepo(pgeMetadata.getMetadata(MIME_EXTRACTOR_REPO));
} else {
crawler = new StdProductCrawler();
}
crawler.setClientTransferer(pgeMetadata
.getMetadata(INGEST_CLIENT_TRANSFER_SERVICE_FACTORY));
crawler.setFilemgrUrl(pgeMetadata.getMetadata(INGEST_FILE_MANAGER_URL));
String crawlerConfigFile = pgeMetadata.getMetadata(CRAWLER_CONFIG_FILE);
if (!Strings.isNullOrEmpty(crawlerConfigFile)) {
crawler.setApplicationContext(
new FileSystemXmlApplicationContext(crawlerConfigFile));
List<String> actionIds = pgeMetadata.getAllMetadata(ACTION_IDS);
if (actionIds != null) {
crawler.setActionIds(actionIds);
}
}
crawler.setRequiredMetadata(pgeMetadata.getAllMetadata(REQUIRED_METADATA));
crawler.setCrawlForDirs(Boolean.parseBoolean(pgeMetadata
.getMetadata(CRAWLER_CRAWL_FOR_DIRS)));
crawler.setNoRecur(!Boolean.parseBoolean(
pgeMetadata.getMetadata(CRAWLER_RECUR)));
logger.debug("Passing Workflow Metadata to CAS-Crawler as global metadata . . .");
crawler.setGlobalMetadata(pgeMetadata.asMetadata(PgeMetadata.Type.DYNAMIC));
logger.debug("Created ProductCrawler [{}]", crawler.getClass().getCanonicalName());
return crawler;
}
@Before
public void setUp() throws Exception {
super.setUp();
this.preconditions = new LinkedList<String>();
this.preconditions.add("CheckThatDataFileSizeIsGreaterThanZero");
this.preconditions.add("CheckThatDataFileExists");
this.preconditions.add("CheckDataFileMimeType");
File preCondFile = getTestDataFile("/met_extr_preconditions.xml");
this.evalUtils = new PreCondEvalUtils(new FileSystemXmlApplicationContext("file:" + preCondFile.getAbsolutePath()));
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileSystemXmlApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("R:/opt/hjf/chinaot_core/core-sc.xml");
ConfigurableListableBeanFactory configurableListableBeanFactory = fileSystemXmlApplicationContext.getBeanFactory();
Map<String, Object> contractServiceBeans = configurableListableBeanFactory.getBeansWithAnnotation(ContractService.class);
for(Map.Entry<String, Object> contractServiceBean : contractServiceBeans.entrySet()){
System.out.println(contractServiceBean.getKey() + "\t" + contractServiceBean.getValue());
}
}
protected ConfigurableApplicationContext createContext(String dsContext) {
String prefix = "src/test/resources/";
return new FileSystemXmlApplicationContext(new String[] {
prefix + dsContext,
prefix + "SpringTxnPersistentWorkflowTest/persistent-engine-unittest-context.xml",
prefix + "unittest-context.xml" });
}