Today, we see spring MVC using the Java Validation Api (JSR-303) for validation and need to load a specific implementation (such as Hibernate Validator), which is not a problem at all, but it suddenly occurred to me what kind of loading process it was. , which means why can spring find hibernate validator as a concrete implementation of JSR-303?
1. The SPI mechanism in Java
This article is relatively easy to understand about the SPI mechanism of Java and does not make more records. Http://www.cnblogs.com/javaee6/p/3714719.html
Below is a small example of how the SPI mechanism and the reflection class name are used to obtain the service (HELLOAPI)
First, give the service interface, export it as a jar package, Hello-api.jar
Package Helloapi; Public Interface Hello { String say ();}
Here is a concrete implementation of it:
Package Helloimpl; Import Helloapi.hello; Public class Implements Hello { @Override public String Say () { return "Hello Massclouds "; }}
To export this implementation as a jar package, but in order to use the Java SPI mechanism, we need to add the Services folder in the Meta-inf of the exported jar package and add a file in it, with the implementation of the interface Helloapi.hello as the name to implement the class Helloimpl.helloimpl for content.
The last is to use SPI and reflection to get the service separately.
Hello hello = null ; // load the implementation class of the Hello API using the Java SPI mechanism serviceloader Class <Hello> iter = Serviceloader.iterator (); if (Iter.hasnext ()) {Hello = Iter.next (); } System.out.println (Hello.say ()); // Hello = (Hello) Class.forName ("Helloimpl.helloimpl"
Look back and think about the way JDBC is loaded, just like I did in the example above. These two ways must be SPI better, the use of class name reflection is essentially hard coding it!
2. How to load Hibernate validator as a JSR-303 implementation
We open Hibernate validator jar package to see.
The content of this file is exactly the implementation of Org.hibernate.validator.HibernateValidator. As for the specific spring is how to do I do not study in detail, haha!!!
The SPI mechanism of Java