Spring ME2reflection to gather data about the object graph to construct, it relies on 'compile time' source codeanalysis only. And in order to instantiate the classes, it uses plain old vanilla Java code.In order to illustrate the difference, Example 1, “'Classic' Spring Approach” shows the classicapproach to Spring bean construction and configuration. It's a simplified example, and it omits theslew of exceptions that you would need to catch, but you probably get the picture.
Example 1. 'Classic' Spring Approach
Class cl = Class.forName("Person");Object instance = cl.newInstance();Method meth = cl.getDeclaredMethod("setName");method.invoke(instance, new Object[] { "Wilfred Springer" });
Example 2, “Spring ME Approach” illustrates the Spring ME approach. It looks ridiculously simple, andin fact, it is.
Example 2. Spring ME Approach
Person instance = new Person();instance.setName("Wilfred Springer");
The important thing to note here is that both examples could be based on the same snippet of Spring configuration, such as the snippet in Example 3, “Example configuration”. The 'classic' Springexample interprets it at runtime; Spring ME generates source from it at build time.
Example 3. Example configuration
<bean id="..." class="Person"><property name="name" value="Wilfred Springer"/></bean>
Now, the smart readers might start wondering where the type information is coming from. After all,the bean configuration does not provide it. How do we know if the value "Wilfred Springer" actuallyrepresents a String, and not something else? A primitive int, for instance?
1
The answer is simple, thatdata is gathered build time as well, by analyzing the sources.
3Show me an example
In order to understand what this means in reality, let's look at a simple example example first. In thissimple example, we define two different classes: Teachers and Courses. A teacher can teach manycourses. Each of these courses has a certain topic.
1
Note that the code that would have to be generated in Example 2, “Spring ME Approach” would need to be different if the name propertywould be an int. I leave it as an exercise to the reader to figure out how it would be different.
Add a Comment
springerwleft a comment