Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Ordered of Spring core interface

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

1. Introduction of Ordered interface

An Ordered interface is provided in Spring. It is known from the meaning of the word that the function of the Ordered interface is to sort.

The Spring framework is a framework that uses a lot of policy design patterns, which means that there are many implementation classes with the same interface, so there must be a priority issue. So Spring provides Ordered as an interface to handle the priority of the same interface implementation class.

Second, Ordered interface analysis

1. Definition of Ordered API:

Public interface Ordered {/ * * Useful constant for the highest precedence value. * @ see java.lang.Integer#MIN_VALUE * / int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;/** * Useful constant for the lowest precedence value. * @ see java.lang.Integer#MAX_VALUE * / int LOWEST_PRECEDENCE = Integer.MAX_VALUE;/** * Get the order value of this object. *

Higher values are interpreted as lower priority. As a consequence, * the object with the lowest value has the highest priority (somewhat * analogous to Servlet {@ code load-on-startup} values). *

Same order values will result in arbitrary sort positions for the * affected objects. * @ return the order value * @ see # HIGHEST_PRECEDENCE * @ see # LOWEST_PRECEDENCE * / int getOrder ()

}

The interface card has only one method getOrder () and two variables HIGHEST_PRECEDENCE highest (minimum value) and LOWEST_PRECEDENCE lowest level (maximum value).

2. OrderComparator class: a comparator that implements the Comparator interface.

Public class OrderComparator implements Comparator {/ * * Shared default instance of OrderComparator. * / public static final OrderComparator INSTANCE = new OrderComparator (); public int compare (Object o1, Object O2) {boolean p1 = (o1 instanceof PriorityOrdered); boolean p2 = (O2 instanceof PriorityOrdered); if (p1 & &! p2) {return-1;} else if (p2 &! p1) {return 1;} / / Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation. Int i1 = getOrder (o1); int i2 = getOrder (O2); return (i1)

< i2) ? -1 : (i1 >

I2)? 1: 0;} / * * Determine the order value for the given object. *

The default implementation checks against the {@ link Ordered} * interface. Can be overridden in subclasses. * @ param obj the object to check * @ return the order value, or {@ code Ordered.LOWEST_PRECEDENCE} as fallback * / protected int getOrder (Object obj) {return (obj instanceof Ordered? ((Ordered) obj). GetOrder (): Ordered.LOWEST_PRECEDENCE);} / * * Sort the given List with a default OrderComparator. *

Optimized to skip sorting for lists with size 0 or 1, * in order to avoid unnecessary array extraction. * @ param list the List to sort * @ see java.util.Collections#sort (java.util.List, java.util.Comparator) * / public static void sort (List list) {if (list.size () > 1) {Collections.sort (list, INSTANCE);}} / * Sort the given array with a default OrderComparator. *

Optimized to skip sorting for lists with size 0 or 1, * in order to avoid unnecessary array extraction. * @ param array the array to sort * @ see java.util.Arrays#sort (Object [], java.util.Comparator) * / public static void sort (Object [] array) {if (array.length > 1) {Arrays.sort (array, INSTANCE);}

Two static sorting methods are provided: sort (List list) for sorting list collections and sort (Object [] array) for sorting Object arrays.

But for the public int compare (Object o1, Object O2) method of the following OrderComparator class, you can see another class PriorityOrdered. The logical parsing of this method is as follows:

If the object o1 is the Ordered interface type and O2 is the PriorityOrdered interface type, then the priority of o2 is higher than o1. If the object o1 is the PriorityOrdered interface type and O2 is the Ordered interface type, then the priority of o1 is higher than that of O2. If both are Ordered interface types or both are PriorityOrdered interface types, call the getOrder method of the Ordered interface to get the order value. The higher the order value, the lower the priority.

To put it simply:

When sorting by the OrderComparator comparator, if one of the two objects implements the PriorityOrdered interface, then this object has a higher priority. If both objects are implementation classes of the PriorityOrdered or Ordered interface, then compare the getOrder method of the Ordered interface to get the order value, the lower the value, the higher the priority.

3. An example of using Ordered interface in Spring

Add: to the spring configuration file, and SpringMVC injects RequestMappingHandlerAdapter and RequestMappingHandlerMapping classes by default. Now that SpringMVC has injected RequestMappingHandlerAdapter and RequestMappingHandlerMapping classes for us by default, what will happen if we configure them again?

When we configure annotation-driven and these two bean. The Spring container has 2 RequestMappingHandlerAdapter and 2 RequestMappingHandlerMapping.

Within DispatcherServlet, there are HandlerMapping (RequestMappingHandlerMapping is its implementation class) collection and HandlerAdapter (RequestMappingHandlerAdapter is its implementation class) collection.

/ / RequestMappingHandlerMapping collection

Private List handlerMappings

/ / HandlerAdapter collection

Private List handlerAdapters

If you look closely at the private void initHandlerMappings (ApplicationContext context) method of the DispatcherServlet class, you can see the following code:

/ / all HandlerMappings defaults to true

If (this.detectAllHandlerMappings) {

/ / Find all HandlerMappings in the ApplicationContext, including ancestor contexts.

Map matchingBeans =

BeanFactoryUtils.beansOfTypeIncludingAncestors (context, HandlerMapping.class, true, false)

If (! matchingBeans.isEmpty ()) {

This.handlerMappings = new ArrayList (matchingBeans.values ())

/ / We keep HandlerMappings in sorted order.

/ / sort

AnnotationAwareOrderComparator.sort (this.handlerMappings)

}

}

AnnotationAwareOrderComparator inherits the OrderComparator class

Take a look at the configured RequestMappingHandlerMapping and RequestMappingHandlerAdapter@Beanbr/ > @ Beanbr/ > @ Bean

Go into the RequestMappingHandlerMapping and RequestMappingHandlerAdapter code to see how their order properties are defined. RequestMappingHandlerMapping// Ordered.LOWEST_PRECEDENCE is only Integer.MAX_VALUEpublic abstract class AbstractHandlerMapping extends WebApplicationObjectSupport implements HandlerMapping, and Ordered {private int order = Integer.MAX_VALUE; AbstractHandlerMapping is the parent of RequestMappingHandlerMapping. RequestMappingHandlerAdapterpublic abstract class AbstractHandlerMethodAdapter extends WebContentGenerator implements HandlerAdapter, Ordered {/ / Ordered.LOWEST_PRECEDENCE is only Integer.MAX_VALUE private int order = Ordered.LOWEST_PRECEDENCE;AbstractHandlerMethodAdapter is the parent class of RequestMappingHandlerAdapter. You can see that when RequestMappingHandlerMapping and RequestMappingHandlerAdapter do not set the order property, the default value of the order property is Integer.MAX_VALUE, which means the lowest priority.

Summary: if a custom RequestMappingHandlerAdapter is configured, and the order value of RequestMappingHandlerAdapter is not set, then the order value of both RequestMappingHandlerAdapter is Integer.MAX_VALUE. So who defines it first, who has the highest priority. Before the custom RequestMappingHandlerAdapter configuration, the configured RequestMappingHandlerAdapter has a high priority, whereas the custom RequestMappingHandlerAdapter has a high priority.

If so, a custom RequestMappingHandlerMapping is configured, and the order value of RequestMappingHandlerMapping is not set. Then the configured RequestMappingHandlerMapping has a high priority because the order of the RequestMappingHandlerMapping is set to 0 internally.

IV. Application

1. Define the interface

Import java.util.Map

Import org.springframework.core.Ordered

Public interface Filter extends Ordered {public void doFiler (Map prams);}

2. Implement the interface

Import java.util.Map; @ Component public class LogFilter implements Filter {private int order = 1; public int getOrder () {return order;} public void setOrder (int order) {this.order = order;} public void doFiler (Map prams) {System.out.println ("print log");} import java.util.Map @ Componentpublic class PowerLogFilter implements Filter {private int order = 2; public int getOrder () {return order;} public void setOrder (int order) {this.order = order;} public void doFiler (Map prams) {System.out.println ("access Control") 3. Public static void main (String [] args) throws Exception {String config = Test.class.getPackage (). GetName (). Replace ('.','/') + "/ bean.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext (config); context.start (); Map filters = context.getBeansOfType (Filter.class); System.out.println (filters.size ()); List f = new ArrayList (filters.values ()); OrderComparator.sort (f); for (int item0; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report