下面列出了怎么用org.springframework.context.ApplicationContext的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
});
}
@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());
}
@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);
}
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);
}
}
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);
}
}
@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);
}
}
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;
}
@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);
}
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);
}
}
/**
* 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);
}
}
@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;
}
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;
}
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");
}
@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\"");
}
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");
}
}
@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();
}
private ComAccessDataService getComAccessDataService() {
if (accessDataService == null) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
accessDataService = (ComAccessDataService) applicationContext.getBean("AccessDataService");
}
return accessDataService;
}
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;
}
@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());
}
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));
}
@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);
}
@Test(expected=BeanCreationException.class)
public void cloudDataSourceWithoutServiceNameSpecified_TwoMixedServiceExist_byId() {
ApplicationContext testContext = getTestApplicationContextWithoutServiceId(
createMysqlService("my-service"), createPostgresqlService("my-service-2"));
testContext.getBean(getConnectorType());
}
@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");
}
@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);
}
@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);
}
}
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;
}
@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();
}
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
// 获取ApplicationContext后,刷新处理器列表
refresh();
}
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..." );
}
}
@Bean
public ServletRegistrationBean messageDispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
return new ServletRegistrationBean(servlet,
"/codenotfound/ws/*");
}