What happens when you have the same compiled class twice in a war deployed in tomcat? (I know it's not a good practice and so on, but what happens behind the scene?)
Are there chances of nasty side-effects?
问题:
回答1:
I would expect the behaviour is the same as anywhere else you have that situation.
The first class found by the class loader will be used, the other will be ignored.
回答2:
If you have one class is in WEB-INF/classes and the other in a jar, the one in WEB-INF/classes will have priority.
If the two classes are in a jar, then one of them will be taken and the other ignored. The one that gets chosen depends on the classloader implementation details and can be different from environment to environment.
So the right class might be chosen in development, and the wrong one in production causing problems that are can be hard to debug. The only way to solve this problem is to remove all duplicate classes from the WAR, this way only one class will always be chosen everywhere.
If you want to detect all these types of duplicates, have a look at this tool I wrote, JHades. It includes a command line tool that lists all duplicates in the WAR:
java -jar jhades-standalone-report.jar path/to/war/webapp.war >>>> Jar overlap report: poi-3.5-FINAL-20090928.jar overlaps with poi-3.7-20101029.jar - total overlapping classes: 990 xercesImpl-2.7.0.jar overlaps with xercesImpl-2.9.1.jar - total overlapping classes: 867 xalan-2.6.0.jar overlaps with xalan-2.7.1.jar - total overlapping classes: 711 bcel-5.2.jar overlaps with xalan-2.7.1.jar - total overlapping classes: 361 xml-apis-2.9.1.jar overlaps with xml-apis.jar - total overlapping classes: 301 jasperreports-applet-3.7.1.jar overlaps with jasperreports-javaflow-3.7.1.jar - total overlapping classes: 254 jasperreports-3.7.1.jar overlaps with jasperreports-applet-3.7.1.jar - total overlapping classes: 254 ... Total number of classes with more than one version: 6169