Ниже приведен мой код, и в результате я получил два журнала.
@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
Почему метод onApplicationEvent интерфейса ApplicationListener в Springboot я реализовал реентерабельный? ⇐ JAVA
Программисты JAVA общаются здесь
1762825980
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;
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79769111/why-is-the-onapplicationevent-method-of-the-applicationlistener-interface-in-spr[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия