Skip to content

Commit 0f3f979

Browse files
committed
Align classloader used to create the JAXBContext
This commit makes sure that JAXBContext.newInstance consistently use the target class classloader to detect the necessary resources. Previously, the current thread's context classloader was used, which could lead to not finding the required JAXB components. Closes gh-33158
1 parent f8875ea commit 0f3f979

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

spring-web/src/main/java/org/springframework/http/codec/xml/JaxbContextContainer.java

+18-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2019 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -51,7 +51,7 @@ public Unmarshaller createUnmarshaller(Class<?> clazz) throws CodecException, JA
5151
private JAXBContext getJaxbContext(Class<?> clazz) throws CodecException {
5252
return this.jaxbContexts.computeIfAbsent(clazz, key -> {
5353
try {
54-
return JAXBContext.newInstance(clazz);
54+
return createJaxbContext(clazz);
5555
}
5656
catch (JAXBException ex) {
5757
throw new CodecException(
@@ -60,4 +60,20 @@ private JAXBContext getJaxbContext(Class<?> clazz) throws CodecException {
6060
});
6161
}
6262

63+
/**
64+
* Create a {@link JAXBContext} for the given type, exposing the class
65+
* ClassLoader as current thread context ClassLoader for the time of
66+
* creating the context.
67+
*/
68+
private JAXBContext createJaxbContext(Class<?> clazz) throws JAXBException {
69+
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
70+
try {
71+
Thread.currentThread().setContextClassLoader(clazz.getClassLoader());
72+
return JAXBContext.newInstance(clazz);
73+
}
74+
finally {
75+
Thread.currentThread().setContextClassLoader(currentClassLoader);
76+
}
77+
}
78+
6379
}

0 commit comments

Comments
 (0)