下面列出了org.springframework.boot.context.event.ApplicationReadyEvent 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
log.info("》》》》》》》》》》城风已就绪《《《《《《《《《《");
CommunityNoticeMapper communityNoticeMapper = event.getApplicationContext().getBean(CommunityNoticeMapper.class);
ProperNoticeMapper properNoticeMapper = event.getApplicationContext().getBean(ProperNoticeMapper.class);
StringRedisTemplate stringRedisTemplate=event.getApplicationContext().getBean(StringRedisTemplate.class);
List<CommunityNotice> communityNotices = communityNoticeMapper.selectAllCommunities();
List<ProperNotice> properNotices = properNoticeMapper.selectAllPropers();
ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet();
HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();
communityNotices.parallelStream()
.forEach(communityNotice ->{
zset.add(RedisConstant.COMMUNITY_NOTICE_ORDER+communityNotice.getCommunityId(),RedisConstant.COMMUNITY_NOTICE_PREFIX+communityNotice.getId(),
new DateTime(communityNotice.getShowtime()).getMillis());
hash.put(RedisConstant.COMMUNITY_NOTICES+communityNotice.getCommunityId(),RedisConstant.COMMUNITY_NOTICE_PREFIX+communityNotice.getId(),
JsonSerializableUtil.obj2String(communityNotice));
});
properNotices.parallelStream()
.forEach(properNotice -> {
zset.add(RedisConstant.PROPER_NOTICE_ORDER+properNotice.getUserId(),RedisConstant.PROPER_NOTICE_PREFIX+properNotice.getId(),
new DateTime(properNotice.getShowtime()).getMillis());
hash.put(RedisConstant.PROPER_NOTICES+properNotice.getUserId(),RedisConstant.PROPER_NOTICE_PREFIX+properNotice.getId(),
JsonSerializableUtil.obj2String(properNotice));
});
}
@EventListener
public void onApplicationReadyEvent(ApplicationReadyEvent event) {
Flux
.interval(Duration.ofMillis(1000))
.flatMap(tick -> repository.findAll())
.map(image -> {
Comment comment = new Comment();
comment.setImageId(image.getId());
comment.setComment(
"Comment #" + counter.getAndIncrement());
return Mono.just(comment);
})
.flatMap(newComment ->
Mono.defer(() ->
controller.addComment(newComment)))
.subscribe();
}
private Set<Class<?>> sources(ApplicationReadyEvent event) {
Method method = ReflectionUtils.findMethod(SpringApplication.class,
"getAllSources");
if (method == null) {
method = ReflectionUtils.findMethod(SpringApplication.class, "getSources");
}
ReflectionUtils.makeAccessible(method);
@SuppressWarnings("unchecked")
Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method,
event.getSpringApplication());
Set<Class<?>> result = new LinkedHashSet<>();
for (Object object : objects) {
if (object instanceof String) {
object = ClassUtils.resolveClassName((String) object, null);
}
result.add((Class<?>) object);
}
return result;
}
private Set<Class<?>> sources(ApplicationReadyEvent event) {
Method method = ReflectionUtils.findMethod(SpringApplication.class,
"getAllSources");
if (method == null) {
method = ReflectionUtils.findMethod(SpringApplication.class, "getSources");
}
ReflectionUtils.makeAccessible(method);
@SuppressWarnings("unchecked")
Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method,
event.getSpringApplication());
Set<Class<?>> result = new LinkedHashSet<>();
for (Object object : objects) {
if (object instanceof String) {
object = ClassUtils.resolveClassName((String) object, null);
}
result.add((Class<?>) object);
}
return result;
}
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
try {
List<InputConference> inputConferencess = CsvReader.loadObjectList(InputConference.class, "csv/conferences.csv");
for (InputConference inputConference : inputConferencess) {
conferenceService.save(InputConference.convert(inputConference));
}
List<InputPerson> speakers = CsvReader.loadObjectList(InputPerson.class, "csv/speakers.csv");
for (InputPerson speaker : speakers) {
personService.save(InputPerson.convert(speaker));
}
List<CsvTalk> talks = CsvReader.loadObjectList(CsvTalk.class, "csv/talks.csv");
for (CsvTalk talk : talks) {
talkService.save(talk.convert(conferenceService, personService));
}
} catch (IOException e) {
log.error("Error loading data: " + e.getMessage());
}
}
/**
* Verify that if a TaskExecutionListener Bean is present that the onTaskFailed method
* is called.
*/
@Test
public void testTaskFail() {
RuntimeException exception = new RuntimeException(EXCEPTION_MESSAGE);
setupContextForTaskExecutionListener();
SpringApplication application = new SpringApplication();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context
.getBean(
DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
this.context.publishEvent(new ApplicationFailedEvent(application, new String[0],
this.context, exception));
this.context.publishEvent(
new ApplicationReadyEvent(application, new String[0], this.context));
TaskExecution taskExecution = new TaskExecution(0, 1, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
verifyListenerResults(true, true, taskExecution, taskExecutionListener);
}
@EventListener
public void simulateComments(ApplicationReadyEvent event) {
Flux
.interval(Duration.ofMillis(1000))
.flatMap(tick -> repository.findAll())
.map(image -> {
Comment comment = new Comment();
comment.setImageId(image.getId());
comment.setComment(
"Comment #" + counter.getAndIncrement());
return Mono.just(comment);
})
.flatMap(newComment ->
Mono.defer(() ->
controller.addComment(newComment)))
.subscribe();
}
@EventListener(ApplicationReadyEvent.class)
public void process() throws Exception {
try (Stream<String> stream = Files.lines(Paths.get(moviesFile.getURI()))) {
stream.forEach(s -> {
Movie movie = Parser.parseMovie(s);
log.info("sending " + movie.getMovieId() + " for movie " + movie.toString() + " to " + MOVIES_TOPIC);
movieTemplate.send(MOVIES_TOPIC, movie.getMovieId(), movie);
});
}
catch (IOException e) {
e.printStackTrace();
}
Random ran = new Random();
while (true) {
int movieId = ran.nextInt(920) + 1;
int rating = 5 + ran.nextInt(6);
Rating rat = new Rating((long) movieId, (double) rating);
log.info(rat.toString());
Thread.sleep(1_000);
this.ratingTemplate.send(KafkaBasicsApplication.RATINGS_TOPIC, rat.getMovieId(), rat);
}
}
@EventListener(ApplicationReadyEvent.class)
public void start() {
ProcessBuilder processBuilder =
new ProcessBuilder(
System.getProperty("os.name").startsWith("Windows") ? "broccoli.cmd" : "broccoli",
"serve",
"--host",
broccoliConfig.getHost(),
"--port",
Integer.toString(broccoliConfig.getPort()));
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
try {
process = processBuilder.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@EventListener(ApplicationReadyEvent.class)
public void initIndicesAfterStartup() {
log.info("Mongo InitIndicesAfterStartup init");
var init = System.currentTimeMillis();
var mappingContext = this.mongoTemplate.getConverter().getMappingContext();
if (mappingContext instanceof MongoMappingContext) {
var resolver = IndexResolver.create(mappingContext);
mappingContext.getPersistentEntities().stream().filter(clazz -> clazz.isAnnotationPresent(Document.class))
.forEach(o -> {
IndexOperations indexOps = this.mongoTemplate.indexOps(o.getType());
resolver.resolveIndexFor(o.getType()).forEach(indexOps::ensureIndex);
});
}
log.info("Mongo InitIndicesAfterStartup took: {}", (System.currentTimeMillis() - init));
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
LOG.debug("初始化环境变量");
} else if (event instanceof ApplicationPreparedEvent) {
LOG.debug("初始化完成");
LOG.debug("初始GameData策划数据");
ConfigManager.loadGameData(this.configPath);
} else if (event instanceof ContextRefreshedEvent) {
LOG.debug("应用刷新");
} else if (event instanceof ApplicationReadyEvent) {
LOG.debug("应用已启动完成");
} else if (event instanceof ContextStartedEvent) {
LOG.debug("应用启动,需要在代码动态添加监听器才可捕获");
} else if (event instanceof ContextStoppedEvent) {
LOG.debug("应用停止");
} else if (event instanceof ContextClosedEvent) {
ApplicationContext context = ((ContextClosedEvent) event).getApplicationContext();
rpcClient = context.getBean(RpcClient.class);
rpcClient.close();
LOG.error("应用关闭");
} else {
}
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
if (properties.isCreateIndexIfNotFound()) {
try {
boolean isPresent = client.indices().exists(getIndexRequest(), RequestOptions.DEFAULT);
if (!isPresent) {
val response = client.indices().create(createIndexRequest(), RequestOptions.DEFAULT);
if (!response.isAcknowledged()) {
throw new RuntimeException("Index creation failed");
}
log.info("Successfully created index: {}", properties.getIndexName());
}
} catch (IOException e) {
log.error("Index creation failed", e);
throw new RuntimeException(e);
}
}
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
if (properties.isCreateIndexIfNotFound() && properties.getDetectorIndexName() != null && properties.getDetectorDocType() != null) {
try {
boolean isPresent = client.indices().exists(getIndexRequest(), RequestOptions.DEFAULT);
if (!isPresent) {
val response = client.indices().create(createIndexRequest(), RequestOptions.DEFAULT);
if (!response.isAcknowledged()) {
throw new RuntimeException("Index creation failed");
}
log.info("Successfully created index: {}", properties.getDetectorIndexName());
}
} catch (IOException e) {
log.error("Index creation failed", e);
throw new RuntimeException(e);
}
}
}
@EventListener(ApplicationReadyEvent.class)
public void serve() throws Exception {
var abstractRSocket = new AbstractRSocket() {
@Override
public Flux<Payload> requestStream(Payload payload) {
return reservationRepository.findAll()
.map(RsocketServer.this::toJson)
.map(DefaultPayload::create);
}
};
SocketAcceptor socketAcceptor = (connectionSetupPayload, rSocket) -> Mono.just(abstractRSocket);
RSocketFactory
.receive()
.acceptor(socketAcceptor)
.transport(this.tcp)
.start()
.subscribe();
}
public static void main(String[] args) throws Exception
{
Optional<JWindow> splash = LoadingSplashScreen
.setupScreen(INCEpTION.class.getResource("splash.png"));
SpringApplicationBuilder builder = new SpringApplicationBuilder();
// Add the main application as the root Spring context
builder.sources(INCEpTION.class).web(SERVLET);
// Signal that we may need the shutdown dialog
builder.properties("running.from.commandline=true");
init(builder);
builder.listeners(event -> {
if (event instanceof ApplicationReadyEvent
|| event instanceof ShutdownDialogAvailableEvent) {
splash.ifPresent(it -> it.dispose());
}
});
builder.run(args);
}
/**
* This method opens the Swagger-UI in the browser on startup of the
* application.
*/
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
Runtime runtime = Runtime.getRuntime();
String url = "http://localhost:" + port + "/swagger-ui.html#";
// Check OS-System
String os = System.getProperty("os.name").toLowerCase();
try {
// Windows
if (os.contains("win")) {
runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
}
// MacOS
if (os.contains("mac")) {
runtime.exec("open " + url);
}
// Linux
if (os.contains("nix") || os.contains("nux")) {
runtime.exec("xdg-open " + url);
}
} catch (IOException e) {
logger.error("Could not open Swagger-UI in the browser!");
}
}
@EventListener
public void handleEvent(Object event) {
// do optional life-cycle management
if (event instanceof ServletWebServerInitializedEvent) {
// when deploy as WAR, this event will not happen
log.debug("Loading Spring Boot");
}
if (event instanceof ApplicationReadyEvent) {
/*
* this event will happen in both WAR and JAR deployment mode
* At this point, Spring Boot is ready
*/
if (!started) {
new MainApps().start();
}
}
// in case Spring Boot fails, it does not make sense to keep the rest of the application running.
if (event instanceof ApplicationFailedEvent) {
log.error("{}", ((ApplicationFailedEvent) event).getException().getMessage());
System.exit(-1);
}
}
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
log.info("application ready");
sysPropertyDs.createSysPropertyTable();
int dbSqlVer = this.upgradeSql();
if (dbSqlVer != HyenaConstants.SQL_VERSION) {
sysPropertyDs.setSqlVersion(HyenaConstants.SQL_VERSION);
}
}
/**
* This function will load all the necessary data from files folder to dynamodb
*/
@EventListener(ApplicationReadyEvent.class)
public void loadDynamoDbTablesAfterStartUp() {
if(isFileImport) {
ScienceMetrixDepartmentCategoryFileImport scienceMetrixDepartmentCategoryFileImport = ApplicationContextHolder.getContext().getBean(ScienceMetrixDepartmentCategoryFileImport.class);
scienceMetrixDepartmentCategoryFileImport.importScienceMetrixDepartmentCategory();
ScienceMetrixFileImport scienceMetrixFileImport = ApplicationContextHolder.getContext().getBean(ScienceMetrixFileImport.class);
scienceMetrixFileImport.importScienceMetrix();
MeshTermFileImport meshTermFileImport = ApplicationContextHolder.getContext().getBean(MeshTermFileImport.class);
meshTermFileImport.importMeshTerms();
IdentityFileImport identityFileImport = ApplicationContextHolder.getContext().getBean(IdentityFileImport.class);
identityFileImport.importIdentity();
if(useGenderStrategy) {
GenderFileImport genderFileImport = ApplicationContextHolder.getContext().getBean(GenderFileImport.class);
genderFileImport.importGender();
} else {
log.info("Gender strategy use is set to false. Please update strategy.gender to true in application.properties file to use it.\n"
+ "Its recommened to use this strategy to get better scores.");
}
if(useScopusArticles) {
InstitutionAfidFileImport institutionAfidFileImport = ApplicationContextHolder.getContext().getBean(InstitutionAfidFileImport.class);
institutionAfidFileImport.importInstitutionAfids();
}
}
}
@Test
void givenApplicationReadyEvent_whenEurekaRegisterEvent_thenCallRegisterEventListener() {
EurekaClient eurekaClient = mock(EurekaClient.class);
EurekaEventsRegistry eventRegister = new EurekaEventsRegistry(eurekaClient,
Collections.singletonList(mock(RibbonMetadataProcessor.class)));
eventRegister.onApplicationEvent(mock(ApplicationReadyEvent.class));
verify(eurekaClient, times(1)).registerEventListener(any());
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
if (!event.getApplicationContext().equals(this.context)) {
return;
}
if (isSpringBootApplication(sources(event))) {
((DefaultListableBeanFactory) event.getApplicationContext().getBeanFactory())
.registerDisposableBean(SHUTDOWN_LISTENER, this);
}
}
@EventListener
public void handleContextRefresh(ApplicationReadyEvent event) throws IOException {
String extDirectConfig = ExtDirectSpringUtil
.generateApiString(event.getApplicationContext());
String userDir = System.getProperty("user.dir");
Files.write(Paths.get(userDir, "client", "api.js"),
extDirectConfig.getBytes(StandardCharsets.UTF_8));
Path clientDir = Paths.get(userDir, "client");
writeI18n(clientDir);
writeEnums(clientDir);
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// 保存插件
if (SystemLoadListener.LOADER.pluginLoader != null) {
SystemLoadListener.LOADER.pluginLoader.save();
SystemLoadListener.LOADER.pluginLoader = null;
}
// 保存模块
if (SystemLoadListener.LOADER.moduleLoader != null) {
SystemLoadListener.LOADER.moduleLoader.save();
SystemLoadListener.LOADER.moduleLoader = null;
}
// 激活插件变化监听
activeListener();
}
/**
* Will execute the targeting of the Data Flow server ONLY if the shell
* is executing shell command passed directly from the console using
* {@code --spring.shell.commandFile}.
*
* see also: https://github.com/spring-projects/spring-shell/issues/252
*/
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// Only invoke if the shell is executing in the same application context as the data flow server.
if (!initialized && this.commandLine.getShellCommandsToExecute() != null) {
triggerTarget();
}
}
/**
* Verify that if a TaskExecutionListener Bean is present that the onTaskEnd method is
* called.
*/
@Test
public void testTaskUpdate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener = this.context
.getBean(
DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
this.context.publishEvent(new ApplicationReadyEvent(new SpringApplication(),
new String[0], this.context));
TaskExecution taskExecution = new TaskExecution(0, 0, "wombat", new Date(),
new Date(), null, new ArrayList<>(), null, null);
verifyListenerResults(true, false, taskExecution, taskExecutionListener);
}
@EventListener(ApplicationReadyEvent.class)
public void setUpData() {
LOGGER.info("Setting up test table BOOK...");
try {
r2dbcClient.execute("CREATE TABLE BOOK ("
+ " ID STRING(36) NOT NULL,"
+ " TITLE STRING(MAX) NOT NULL"
+ ") PRIMARY KEY (ID)")
.fetch().rowsUpdated().block();
} catch (Exception e) {
LOGGER.info("Failed to set up test table BOOK", e);
return;
}
LOGGER.info("Finished setting up test table BOOK");
}
@EventListener
@Order(Ordered.LOWEST_PRECEDENCE)
public void onApplicationReady(ApplicationReadyEvent event) {
if (autoRegister) {
startRegisterTask();
}
}
@EventListener(ApplicationReadyEvent.class)
public void demo() throws Exception {
this.rr.deleteAll();
Stream.of("A", "B", "C")
.map(name -> new Reservation(null, name))
.map(this.rr::save)
.forEach(log::info);
}
/**
* 启动后, 连接行情数据源
*/
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady(){
state = ServiceState.Ready;
executorService.execute(()->{
for(AbsMarketDataProducer p:producers.values()) {
if ( p.getState()==ConnState.Initialized ) {
p.connect();
}
}
});
}
@Test
public void resourcesNull() {
Context standardContext = mock(Context.class);
Mockito.when(standardContext.getResources()).thenReturn(null);
Mockito.when(standardContext.getAddWebinfClassesResources()).thenReturn(Boolean.FALSE);
JsfTomcatContextCustomizer jsfTomcatContextCustomizer = new JsfTomcatContextCustomizer();
jsfTomcatContextCustomizer.customize(standardContext);
JsfTomcatApplicationListener jsfTomcatApplicationListener = new JsfTomcatApplicationListener(jsfTomcatContextCustomizer.getContext());
jsfTomcatApplicationListener.onApplicationEvent(mock(ApplicationReadyEvent.class));
assertThat(jsfTomcatApplicationListener)
.isNotNull();
}