Почему метод onApplicationEvent интерфейса ApplicationListener в Springboot я реализовал реентерабельный?JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Почему метод onApplicationEvent интерфейса ApplicationListener в Springboot я реализовал реентерабельный?

Сообщение Anonymous »

Ниже приведен мой код, и в результате я получил два журнала.

@Slf4j
@Component
public class HandlerMappingAfterSpringInitializationExporter implements ApplicationListener {
@Autowired
private ApplicationContext applicationContext;
private volatile boolean exported = false;

private volatile int count = 0;

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

synchronized (HandlerMappingAfterSpringInitializationExporter.class) {
count+=1;

if (exported) {
return;
}
try {
//getAllServletFilters and getAllSpringManagedInterceptor method details are listed at the end.
getAllServletFilters();
getAllSpringManagedInterceptor();
//here are some other io operations like File.write() which are ignored
log.info("the value of count is :{}",count);
log.info("the value of exported is :{}",exported)

} catch (Exception e) {
System.err.println("导出Web组件信息失败: " + e.getMessage());
e.printStackTrace();
}

exported = true;
}
}
}

Первый из них показан ниже
"the value of count is :1"
"the value of exported is :false"

Второй показан ниже
"the value of count is :2"
"the value of exported is :false"

Вот моя версия весенней загрузки

org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE



Я пишу код для того, чтобы экспортировать некоторую информацию о Spring Bean только один раз, поэтому я использую synchronizde и volutable.
Я зарегистрировал информацию о потоке и обнаружил, что у них одно и то же имя «main».
Интересно, как это произошло. Спасибо.
ниже приведено дополнение к пропущенному коду.
public List getAllServletFilters() {
List< WebInterceptorFilterInfo> filters = new ArrayList();

if (applicationContext instanceof WebApplicationContext) {
WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
ServletContext servletContext = webApplicationContext.getServletContext();

if (servletContext != null) {

Map filterRegistrationMap = (Map) servletContext.getFilterRegistrations();

for(Map.Entry e: filterRegistrationMap.entrySet()){
FilterRegistration filterRegistration = e.getValue();
String filterName =filterRegistration.getName();
String fullClassName = filterRegistration.getClassName();
WebInterceptorFilterInfo filterInfo = new WebInterceptorFilterInfo();
filterInfo.setComponentName(filterName);
filterInfo.setComponentType("servelet-filter");
filterInfo.setFullClassName(fullClassName);
filters.add(filterInfo);
}

} else {
System.err.println("fail to obtain ServletContext:can not get ServletContext in WebApplicationContext");
}
} else {
System.err.println("can not get ServletContext:current ApplicationContext is not WebApplicationContext");
}

return filters;
}

public List getAllSpringManagedInterceptor() {
List result = new ArrayList();

Map interceptorBeans = applicationContext.getBeansOfType(HandlerInterceptor.class);
for (Map.Entry entry : interceptorBeans.entrySet()) {
WebInterceptorFilterInfo info = new WebInterceptorFilterInfo();
info.setComponentName(entry.getKey());
info.setComponentType("HandlerInterceptor");
info.setFullClassName(entry.getValue().getClass().getName());
result.add(info);
}

Collections.sort(result, Comparator.comparing(WebInterceptorFilterInfo::getComponentType));
return result;
}



Подробнее здесь: https://stackoverflow.com/questions/797 ... ace-in-spr
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»