Java Code Examples for org.springframework.context.ApplicationContext
The following examples show how to use
org.springframework.context.ApplicationContext.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: spring-analysis-note Author: Vip-Augus File: BshScriptFactoryTests.java License: MIT License | 6 votes |
@Test public void nonStaticPrototypeScript() { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshRefreshableContext.xml", getClass()); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger)); assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable); assertEquals("Hello World!", messenger.getMessage()); assertEquals("Hello World!", messenger2.getMessage()); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); assertEquals("Bye World!", messenger.getMessage()); assertEquals("Byebye World!", messenger2.getMessage()); Refreshable refreshable = (Refreshable) messenger; refreshable.refresh(); assertEquals("Hello World!", messenger.getMessage()); assertEquals("Byebye World!", messenger2.getMessage()); assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); }
Example #2
Source Project: web3sdk Author: FISCO-BCOS File: ECKeyPairTest.java License: Apache License 2.0 | 6 votes |
@Test public void verifySecp256ECDSASignTest0() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:applicationContext-keystore-sample.xml"); // test p12 P12Manager p12 = context.getBean(P12Manager.class); ECKeyPair ecKeyPair = p12.getECKeyPair(); ECDSASign ecdsaSign = new ECDSASign(); String message = "message"; Sign.SignatureData signatureData = ecdsaSign.secp256SignMessage(message.getBytes(), ecKeyPair); SHA3Digest sha3Digest = new SHA3Digest(); byte[] hash = sha3Digest.hash(message.getBytes()); boolean verify = ecdsaSign.secp256Verify(hash, ecKeyPair.getPublicKey(), signatureData); assertEquals(verify, true); }
Example #3
Source Project: MicroCommunity Author: java110 File: OrderServiceApplicationStart.java License: Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { try { ApplicationContext context = SpringApplication.run(OrderServiceApplicationStart.class, args); //服务启动加载 ServiceStartInit.initSystemConfig(context); //加载事件数据 //EventConfigInit.initSystemConfig(); //刷新缓存 flushMainCache(args); }catch (Throwable e){ logger.error("系统启动失败",e); } }
Example #4
Source Project: automon Author: stevensouza File: HelloWorld.java License: Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld hw = (HelloWorld) context.getBean("helloWorld"); int loops = (args==null || args.length==0) ? 1 : Integer.valueOf(args[0]); for (int i=0;i<loops;i++) { System.out.println(" ** loop "+i+" of "+loops); System.out.println(" ** "+hw.mySpringMonitoring()); System.out.println(" ** "+hw.getFirstName()); System.out.println(" ** "+hw.getLastName()); try { hw.iMessedUp(); } catch (RuntimeException exception) { // hidden exception } Thread.sleep(1000); } }
Example #5
Source Project: breeze Author: politie File: TopologyStarter.java License: Apache License 2.0 | 6 votes |
@Override public void run() { properties.put(Config.TOPOLOGY_NAME, ID); Config config = stormConfig(properties); ApplicationContext spring = SingletonApplicationContext.loadXml(config, MAIN_CONTEXT); try { StormTopology topology = spring.getBean(ID, StormTopology.class); Properties systemProperties = System.getProperties(); if (systemProperties.containsKey(LOCAL_RUN_PARAM)) { String timeout = systemProperties.getProperty(LOCAL_RUN_PARAM); if (! hasText(timeout)) timeout = LOCAL_RUN_DEFAULT_TIMEOUT; long ms = 1000L * Integer.parseInt(timeout); LocalCluster cluster = new LocalCluster(); cluster.submitTopology(ID, config, topology); sleep(ms); cluster.shutdown(); } else StormSubmitter.submitTopology(ID, config, topology); } catch (Exception e) { e.printStackTrace(); exit(255); } }
Example #6
Source Project: micro-server Author: aol File: TomcatApplicationFactory.java License: Apache License 2.0 | 6 votes |
public ServerApplication createApp(final Module module, final ApplicationContext rootContext) { ModuleDataExtractor extractor = new ModuleDataExtractor(module); PersistentList resources = extractor.getRestResources(rootContext); MicroserverEnvironment microserverEnvironment = rootContext.getBean(MicroserverEnvironment.class); microserverEnvironment.assureModule(module); String fullRestResource = "/" + module.getContext() + "/*"; ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(), resources, rootContext, fullRestResource, module); List<FilterData> filterDataList = extractor.createFilteredDataList(serverData); List<ServletData> servletDataList = extractor.createServletDataList(serverData); TomcatApplication app = new TomcatApplication( new AllData(serverData, filterDataList, servletDataList, module.getListeners(serverData), module.getRequestListeners(serverData))); return app; }
Example #7
Source Project: kork Author: spinnaker File: PluginsAutoConfiguration.java License: Apache License 2.0 | 6 votes |
@Bean public static SpinnakerPluginManager pluginManager( ServiceVersion serviceVersion, VersionManager versionManager, PluginStatusProvider pluginStatusProvider, ApplicationContext applicationContext, ConfigFactory configFactory, List<SdkFactory> sdkFactories, PluginBundleExtractor pluginBundleExtractor) { return new SpinnakerPluginManager( serviceVersion, versionManager, pluginStatusProvider, configFactory, sdkFactories, Objects.requireNonNull( applicationContext.getEnvironment().getProperty("spring.application.name")), determineRootPluginPath(applicationContext), pluginBundleExtractor); }
Example #8
Source Project: Spring-Framework-Essentials Author: kousen File: RunDemo.java License: MIT License | 5 votes |
public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext( AppConfig.class, AppConfig.class); System.out.println(context.getBeanDefinitionCount()); for (String name : context.getBeanDefinitionNames()) { System.out.println(name); } }
Example #9
Source Project: alfresco-repository Author: Alfresco File: AlfrescoPeople.java License: GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void after() { // Set up required services ApplicationContext ctxt = getApplicationContext(); final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) ctxt.getBean("retryingTransactionHelper"); transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { for (Map.Entry<String, NodeRef> entry : usersPersons.entrySet()) { deletePerson(entry.getKey()); } return null; } }); }
Example #10
Source Project: spring-analysis-note Author: Vip-Augus File: ConvertingEncoderDecoderSupport.java License: MIT License | 5 votes |
/** * Called to initialize the encoder/decoder. * @see javax.websocket.Encoder#init(EndpointConfig) * @see javax.websocket.Decoder#init(EndpointConfig) */ public void init(EndpointConfig config) { ApplicationContext applicationContext = getApplicationContext(); if (applicationContext != null && applicationContext instanceof ConfigurableApplicationContext) { ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); beanFactory.autowireBean(this); } }
Example #11
Source Project: spring-analysis-note Author: Vip-Augus File: MessageMappingMessageHandler.java License: MIT License | 5 votes |
@Override protected List<? extends HandlerMethodArgumentResolver> initArgumentResolvers() { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(); ApplicationContext context = getApplicationContext(); ConfigurableBeanFactory beanFactory = (context instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext) context).getBeanFactory() : null); // Annotation-based resolvers resolvers.add(new HeaderMethodArgumentResolver(this.conversionService, beanFactory)); resolvers.add(new HeadersMethodArgumentResolver()); resolvers.add(new DestinationVariableMethodArgumentResolver(this.conversionService)); // Type-based... if (KotlinDetector.isKotlinPresent()) { resolvers.add(new ContinuationHandlerMethodArgumentResolver()); } // Custom resolvers resolvers.addAll(getArgumentResolverConfigurer().getCustomResolvers()); // Catch-all resolvers.add(new PayloadMethodArgumentResolver( this.decoders, this.validator, getReactiveAdapterRegistry(), true)); return resolvers; }
Example #12
Source Project: cerberus-source Author: cerberustesting File: ReadLogEvent.java License: GNU General Public License v3.0 | 5 votes |
private AnswerItem<JSONObject> findDistinctValuesOfColumn(ApplicationContext appContext, HttpServletRequest request, String columnName) throws JSONException { AnswerItem<JSONObject> answer = new AnswerItem<>(); JSONObject object = new JSONObject(); logEventService = appContext.getBean(ILogEventService.class); String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), ""); String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "Time,login,Page,Action,log"); String columnToSort[] = sColumns.split(","); List<String> individualLike = new ArrayList<>(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(","))); Map<String, List<String>> individualSearch = new HashMap<>(); for (int a = 0; a < columnToSort.length; a++) { if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) { List<String> search = new ArrayList<>(Arrays.asList(request.getParameter("sSearch_" + a).split(","))); if (individualLike.contains(columnToSort[a])) { individualSearch.put(columnToSort[a] + ":like", search); } else { individualSearch.put(columnToSort[a], search); } } } AnswerList logList = logEventService.readDistinctValuesByCriteria(searchParameter, individualSearch, columnName); object.put("distinctValues", logList.getDataList()); answer.setItem(object); answer.setResultMessage(logList.getResultMessage()); return answer; }
Example #13
Source Project: zuihou-admin-boot Author: zuihou File: AuthorityDatabaseAutoConfiguration.java License: Apache License 2.0 | 5 votes |
public AuthorityDatabaseAutoConfiguration(MybatisPlusProperties properties, DatabaseProperties databaseProperties, ObjectProvider<Interceptor[]> interceptorsProvider, ObjectProvider<TypeHandler[]> typeHandlersProvider, ObjectProvider<LanguageDriver[]> languageDriversProvider, ResourceLoader resourceLoader, ObjectProvider<DatabaseIdProvider> databaseIdProvider, ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider, ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider, ApplicationContext applicationContext) { super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider, languageDriversProvider, resourceLoader, databaseIdProvider, configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext); log.debug("检测到 zuihou.database.multiTenantType!=DATASOURCE,加载了 AuthorityDatabaseAutoConfiguration"); }
Example #14
Source Project: spring-cloud-function Author: spring-cloud File: FunctionDeployerTests.java License: Apache License 2.0 | 5 votes |
@Test public void testWithLegacyProperties() throws Exception { String[] args = new String[] { "--function.location=target/it/bootapp/target/bootapp-1.0.0.RELEASE-exec.jar", "--function.name=uppercase" }; ApplicationContext context = SpringApplication.run(DeployerApplication.class, args); FunctionCatalog catalog = context.getBean(FunctionCatalog.class); Function<Message<byte[]>, Message<byte[]>> function = catalog.lookup("uppercase", "application/json"); Message<byte[]> result = function .apply(MessageBuilder.withPayload("\"bob\"".getBytes(StandardCharsets.UTF_8)).build()); assertThat(new String(result.getPayload(), StandardCharsets.UTF_8)).isEqualTo("\"BOB\""); }
Example #15
Source Project: sctalk Author: ccfish86 File: MessageServerApplication.java License: Apache License 2.0 | 5 votes |
public static void main(String[] args) { SpringApplication app = new SpringApplication(MessageServerApplication.class); ApplicationContext applicationContext = app.run(args); try { applicationContext.getBean(MessageServerStarter.class).start(args); } catch (Exception e) { logger.error("Shutdown with errors ", e); SpringApplication.exit(applicationContext); } finally { logger.info("done"); } }
Example #16
Source Project: spring-cloud-vault Author: spring-cloud File: VaultVersionedKvBackendConfigTests.java License: Apache License 2.0 | 5 votes |
@Test public void shouldContainVaultBeans() { // Beans are registered in parent (bootstrap) context. ApplicationContext parent = this.applicationContext.getParent(); assertThat(parent.getBeanNamesForType(VaultTemplate.class)).isNotEmpty(); assertThat(parent.getBeanNamesForType(LeasingVaultPropertySourceLocator.class)) .isNotEmpty(); }
Example #17
Source Project: openemm Author: agnitas-org File: ComOnePixelCount.java License: GNU Affero General Public License v3.0 | 5 votes |
private ComAccessDataService getComAccessDataService() { if (accessDataService == null) { ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); accessDataService = (ComAccessDataService) applicationContext.getBean("AccessDataService"); } return accessDataService; }
Example #18
Source Project: cerberus-source Author: cerberustesting File: UpdateCampaign.java License: GNU General Public License v3.0 | 5 votes |
private List<ScheduleEntry> getScheduleEntryListFromParameter(HttpServletRequest request, ApplicationContext appContext, String campaign, JSONArray json) throws JSONException { List<ScheduleEntry> scheList = new ArrayList<>(); IScheduleEntryService scheService = appContext.getBean(IScheduleEntryService.class); IFactoryScheduleEntry scheFactory = appContext.getBean(IFactoryScheduleEntry.class); PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS); String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding(); for (int i = 0; i < json.length(); i++) { JSONObject tcsaJson = json.getJSONObject(i); // Parameter that are already controled by GUI (no need to decode) --> We SECURE them boolean delete = tcsaJson.getBoolean("toDelete"); String cronExpression = policy.sanitize(tcsaJson.getString("cronDefinition")); String active = policy.sanitize(tcsaJson.getString("active")); String strId = tcsaJson.getString("ID"); String desc = tcsaJson.getString("description"); String type = "CAMPAIGN"; String name = campaign; int id; if (strId.isEmpty()) { id = 0; } else { try { id = Integer.parseInt(strId); } catch (NumberFormatException e) { LOG.warn("Unable to parse pool size: " + strId + ". Applying default value"); id = 0; } } Timestamp timestampfactice = new Timestamp(System.currentTimeMillis()); if (!delete) { ScheduleEntry sch = scheFactory.create(id, type, name, cronExpression, timestampfactice, active, desc, request.getRemoteUser(), timestampfactice, request.getRemoteUser(), timestampfactice); scheList.add(sch); } } return scheList; }
Example #19
Source Project: spring-cloud-connectors Author: spring-cloud File: DataSourceXmlConfigTest.java License: Apache License 2.0 | 5 votes |
@Test(expected=BeanCreationException.class) public void cloudDataSourceWithoutServiceNameSpecified_TwoMixedServiceExist_byType() { ApplicationContext testContext = getTestApplicationContext(getWithoutServiceIdContextFileName(), createMysqlService("my-service"), createPostgresqlService("my-service-2")); testContext.getBean("my-service", getConnectorType()); }
Example #20
Source Project: waltz Author: finos File: AssessmentGenerator.java License: Apache License 2.0 | 5 votes |
private RatingScheme getOrCreateConfidentialityRatingScheme(ApplicationContext ctx) { return getOrCreateRatingScheme( ctx, "Confidentiality", tuple("C", "Confidential", ColorUtilities.HexStrings.AMBER), tuple("S", "Strictly Confidential", ColorUtilities.HexStrings.RED), tuple("I", "Internal", ColorUtilities.HexStrings.BLUE), tuple("P", "Public", ColorUtilities.HexStrings.GREEN), tuple("U", "Unrated", ColorUtilities.HexStrings.GREY)); }
Example #21
Source Project: qconfig Author: qunarcorp File: UpdateConfigServlet.java License: MIT License | 5 votes |
@Override public void init(ServletConfig config) throws ServletException { super.init(config); ApplicationContext context = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (context == null) { throw new ServletException("init failed"); } this.configStore = context.getBean(ConfigStore.class); Preconditions.checkNotNull(this.configStore); }
Example #22
Source Project: spring-cloud-connectors Author: spring-cloud File: DataSourceJavaConfigTest.java License: Apache License 2.0 | 5 votes |
@Test(expected=BeanCreationException.class) public void cloudDataSourceWithoutServiceNameSpecified_TwoMixedServiceExist_byId() { ApplicationContext testContext = getTestApplicationContextWithoutServiceId( createMysqlService("my-service"), createPostgresqlService("my-service-2")); testContext.getBean(getConnectorType()); }
Example #23
Source Project: compass Author: sogou-biztech File: ShardJdbcTemplatePlanServiceTest.java License: Apache License 2.0 | 5 votes |
@Before public void setUp() { ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "classpath*:/conf/aggregation/test-aggregation-shardjdbctemplate.xml", "classpath*:/datasource/shard/test-shard-*.xml" }); service = (ShardJdbcTemplatePlanService) ctx.getBean("planService"); }
Example #24
Source Project: spring-reactive-sample Author: hantsy File: Application.java License: GNU General Public License v3.0 | 5 votes |
@Profile("default") @Bean public HttpServer nettyHttpServer(ApplicationContext context) { HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build(); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); HttpServer httpServer = HttpServer.create().host("localhost").port(this.port); return httpServer.handle(adapter); }
Example #25
Source Project: thinking-in-spring-boot-samples Author: mercyblitz File: SpringBoot13ActuatorEndpointsBootstrap.java License: Apache License 2.0 | 5 votes |
@Override public void setApplicationContext(ApplicationContext context) throws BeansException { // 复制 BeansEndpoint#setApplicationContext(ApplicationContext) 方法实现 if (context.getEnvironment() .getProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME) == null) { this.liveBeansView.setApplicationContext(context); } }
Example #26
Source Project: schema-evolution-samples Author: viniciusccarvalho File: AvroCodecAutoConfiguration.java License: Apache License 2.0 | 5 votes |
public Codec avroCodec(AvroCodecProperties properties, SchemaRegistryClient schemaRegistryClient, ApplicationContext ctx) throws Exception{ AvroCodec codec = new AvroCodec(); codec.setProperties(properties); codec.setSchemaRegistryClient(schemaRegistryClient); codec.setResolver(new PathMatchingResourcePatternResolver(ctx)); codec.init(); return codec; }
Example #27
Source Project: spring-cloud-stream Author: spring-cloud File: BindingServiceTests.java License: Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testBindingAutostartup() throws Exception { ApplicationContext context = new SpringApplicationBuilder(FooConfiguration.class) .web(WebApplicationType.NONE).run("--spring.jmx.enabled=false", "--spring.cloud.stream.bindings.input.consumer.auto-startup=false"); BindingService bindingService = context.getBean(BindingService.class); Field cbField = ReflectionUtils.findField(BindingService.class, "consumerBindings"); cbField.setAccessible(true); Map<String, Object> cbMap = (Map<String, Object>) cbField.get(bindingService); Binding<?> inputBinding = ((List<Binding<?>>) cbMap.get("input")).get(0); assertThat(inputBinding.isRunning()).isFalse(); }
Example #28
Source Project: Milkomeda Author: yizzuide File: AbstractHydrogenLoader.java License: MIT License | 5 votes |
@Override public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; // 获取ApplicationContext后,刷新处理器列表 refresh(); }
Example #29
Source Project: usergrid Author: apache File: ShutdownListener.java License: Apache License 2.0 | 5 votes |
public void contextDestroyed(ServletContextEvent sce) { logger.info("ShutdownListener invoked"); ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(sce.getServletContext()); Injector injector = ctx.getBean(Injector.class); ActorSystemManager actorSystemManager = injector.getInstance(ActorSystemManager.class); // leave akka cluster actorSystemManager.leaveCluster(); DataStaxCluster dataStaxCluster = injector.getInstance(DataStaxCluster.class); // shutdown the connections to the database dataStaxCluster.shutdown(); boolean started = Boolean.parseBoolean( properties.getProperty(JobServiceBoostrap.START_SCHEDULER_PROP, "true")); if ( started ) { schedulerService.stopAsync(); schedulerService.awaitTerminated(); logger.info( "Stopped Scheduler Service..." ); } }
Example #30
Source Project: spring-ws Author: code-not-found File: WebServiceConfig.java License: MIT License | 5 votes |
@Bean public ServletRegistrationBean messageDispatcherServlet( ApplicationContext applicationContext) { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); return new ServletRegistrationBean(servlet, "/codenotfound/ws/*"); }