我有一个bean通过静态块实例化一个模式,因此它为MyClass的每个实例加载一次。但是我从来没有看到日志记录(当我输入错误的文件路径时只看到它一次,因此这是从异常中记录的)。如果我用System.out.println()
替换日志记录,它将显示在控制台中。
我的项目使用SLF4J和LOG4J。我已经看到了这个问题:Putting Logger.info in static block声称LOG4J应该在静态块执行时初始化。我的预感是,使用SLF4J不再保证。这是对的吗?
private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
private static Schema XSD_SCHEMA = null;
static {
// NB The logging in this static block does not always appear in the output. It seems
// that the indirection between SLF4J and LOG4J causes slow initialization of the logging
// framework.
if (XSD_SCHEMA != null) {
LOGGER.info("Reading schema...");
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = null;
try {
schema = sf.newSchema(new File("some.xsd"));
LOGGER.info("Read schema successfully, using validation...");
} catch (SAXException e) {
LOGGER.error("Could not load validation schema, not using validation (Reason {})",
e);
}
XSD_SCHEMA = schema;
}
}
答案 0 :(得分:1)
简单地省略if if语句
if (XSD_SCHEMA != null) {
实际上,它总是假的,静态块永远不会执行任何有用的。
你不需要它,因为静态块只会被执行一次。