英文:
Why is the static value different from appender(log4j custom appender)?
问题
我在Spring中像这样创建静态变量。
```java
public class A {
private static final Map<String, Session> listMap = new HashMap<>();
public static Map<String, Session> getMap() { return this.listMap.values(); }
public static void addMap(String name, Session s) { return this.listMap.put(name, s); }
}
我在服务层保存。
@Slf4j
public class BService {
public void addSession(String name, Session s) {
A.addMap("a", s);
log.info("added!");
}
}
保存后,我在自定义appender中使用它。(https://www.baeldung.com/log4j2-custom-appender)
@Plugin(
name = "MapAppender",
category = Core.CATEGORY_NAME,
elementType = Appender.ELEMENT_TYPE)
public class MapAppender extends AbstractAppender {
private ConcurrentMap<String, LogEvent> eventMap = new ConcurrentHashMap<>();
protected MapAppender(String name, Filter filter) {
super(name, filter, null);
}
@PluginFactory
public static MapAppender createAppender(
@PluginAttribute("name") String name,
@PluginElement("Filter") Filter filter) {
return new MapAppender(name, filter);
}
@Override
public void append(LogEvent event) {
Map<?, ?> resultMap = A.getMap();
send();
}
}
然而,当执行appender的append()方法时,A.getMap()
返回为空(大小为0)。(在服务层中,A.getMap()返回正确。)
为什么静态值会不同?...
英文:
I make static variable like this in spring.
public class A {
private static final Map<String, Session> listMap = new HashMap<>();
public static Map<String> getMap() { return this.listMap.values() }
public static void addMap(String name, Session s) { return this.listMap.put(name, s) }
}
I save in service layer.
@Slf4j
public class BService {
public void addSession(String name, Session s) {
A.addMap("a", s);
log.info("added!");
}
}
After saving it, I used it in custom appender.(https://www.baeldung.com/log4j2-custom-appender)
@Plugin(
name = "MapAppender",
category = Core.CATEGORY_NAME,
elementType = Appender.ELEMENT_TYPE)
public class MapAppender extends AbstractAppender {
private ConcurrentMap<String, LogEvent> eventMap = new ConcurrentHashMap<>();
protected MapAppender(String name, Filter filter) {
super(name, filter, null);
}
@PluginFactory
public static MapAppender createAppender(
@PluginAttribute("name") String name,
@PluginElement("Filter") Filter filter) {
return new MapAppender(name, filter);
}
@Override
public void append(LogEvent event) {
Map<> resultMap = A.getMap();
send()
}
}
However, when the appender's append() method is executed, A.getMap()
return nothing(size 0). (A.getMap() return correctly in service layer.)
Why is the static value different?..
答案1
得分: 1
listMap
在调用 addSession
时被加载,所以当调用 append()
方法时它是空的。
英文:
listMap
is loaded when you call addSession
so it is empty When append()
method is called
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论