In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today Xiaobian to share with you how to use Spring features to achieve many kinds of interface dynamic invocation of the relevant knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you can learn something after reading this article, let's take a look at it.
Just in time. Mark, check the background.
The org.springframework.beans and org.springframework.context packages are the foundation of the Spring IoC container. Among them, BeanFactory,BeanFactory is the core interface of the IoC container. Its duties include instantiating, locating, configuring objects in the application and establishing dependencies between these objects.
As a subclass of BeanFactory, ApplicationContext has been greatly enhanced in the function of Bean management, and it is easier to integrate with Spring AOP.
What we are going to discuss today is not the implementation principle of BeanFactory or ApplicationContext, but a practical application of ApplicationContext.
The raising of a question
In practical work, we often encounter the situation of one interface and multiple implementation classes, and different implementation classes are used under different conditions.
In terms of usage, it is somewhat similar to the use of SPI, but since SPI is not very convenient to use, what should I do? We can use ApplicationContext's getBeansOfType to achieve the results we need.
First, let's look at the signature of this method, Map getBeansOfType (Class type) throws BeansException.
We can see from the above code that this method returns all the implementation classes of an interface (provided that all implementation classes must be managed by the Spring IoC container).
Next, let's take a look at the problem we have.
"suppose there are multiple modes of transportation from point A to point B, and the cost of each mode is different, and you can choose according to the needs of passengers." (well, I admit that this is a very bad demand, but you can think of similar needs. For example, the payment method, the express delivery company, provides several options on the page, and the business code selects different implementation class instances to call according to different options).
Realize
Going back to our example, according to the requirements of this mode of transportation, our design is as follows: there is an interface for a mode of transportation, and the interface has two ways, one for querying the cost and one for querying the type of the mode of transportation, and at the same time, we can use an enumerated type class to identify the traffic type.
We also need a factory class to find the Bean instance of the traffic type based on the traffic type identification, so that we can use this instance to get the details of the traffic type and the operation of the traffic type.
The code is as follows
Interface:
/ * Traffic mode * / public interface TrafficMode {/ * query traffic mode code * @ return code * / TrafficCode getCode (); / * query the cost of traffic mode (in * @ return fee * / Integer getFee ();}
Enumerate:
/ * Traffic type enumeration * / public enum TrafficCode {TRAIN, BUS}
Interface has two implementation classes:
/ * bus mode * / @ Componentpublic class BusMode implements TrafficMode {@ Override public TrafficCode getCode () {return TrafficCode.BUS;} @ Override public Integer getFee () {return 10000;}} / * Train mode * / @ Componentpublic class TrainMode implements TrafficMode {@ Override public TrafficCode getCode () {return TrafficCode.TRAIN } @ Override public Integer getFee () {return 9000;}}
Factory class:
/ * Traffic mode factory class * / @ Componentpublic class TrafficModeFactory implements ApplicationContextAware {private static Map trafficBeanMap; @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {Map map = applicationContext.getBeansOfType (TrafficMode.class); trafficBeanMap = new HashMap (); map.forEach ((key, value)-> trafficBeanMap.put (value.getCode (), value)) } public static T getTrafficMode (TrafficCode code) {return (T) trafficBeanMap.get (code);}} Verification
With the above code, let's take a look at the effect through the unit test, which is as follows:
@ Test public void testGetTrafficMode () {TrafficMode mode = TrafficModeFactory.getTrafficMode (TrafficCode.BUS); Assert.assertEquals (mode.getFee (). IntValue (), 10000); mode = TrafficModeFactory.getTrafficMode (TrafficCode.TRAIN); Assert.assertEquals (mode.getFee (). IntValue (), 9000);}
What is the result of running it? It must be a yes.
About SPI
At the end of the article, some students may ask: what's the difference between this and SPI? SPI can also achieve the same function. First of all, SPI is a built-in feature of JDK. Although it has a long history, it doesn't mean it's bad, and some scenarios have to be SPI (such as JDBC).
Let's clarify what SPI is and what it is designed to do. The full name of SPI is Service Provider Interface (Service provider Interface) because this is for vendors or plug-ins. A more classic usage is that JDBC,java provides a standard JDBC interface, and each database vendor provides its own database-driven implementation.
The following is the interface of JDBC driver public interface Driver {Connection connect (String var1, Properties var2) throws SQLException; boolean acceptsURL (String var1) throws SQLException; DriverPropertyInfo [] getPropertyInfo (String var1, Properties var2) throws SQLException; int getMajorVersion (); int getMinorVersion (); boolean jdbcCompliant (); Logger getParentLogger () throws SQLFeatureNotSupportedException;} below is the SPI configuration of MySQL's JDBC driver implementation
As far as SPI is concerned, I just want to show that SPI is different from the AP used in our previous example.
In the previous example, what are we using? The full name of Spring's API,API is Application Programming Interface (Application programming Interface). Within an application, using API is a very convenient and direct way.
To sum up, we use API the most in programming. Of course, we also use SPI (although we are not strictly a vendor or plug-in), and using SPI is also a way to solve problems in specific scenarios.
More information about SPI will be introduced later.
SPI convention: when the service provider provides an implementation of the service interface, a file named after the service interface is also created in the META-INF/services/ directory of the jar package.
In this file is the specific implementation class that implements the service interface. When the external program assembles this module, it can find the specific implementation class name through the configuration file in the jar package META-INF/services/, and load the instantiation to complete the injection of the module.
Based on such a convention, it is good to find the implementation class of the service interface without having to make it in the code.
Jdk provides a utility class for service implementation lookup: java.util.ServiceLoader, whose implementation class can be obtained by passing in the interface through its load method.
These are all the contents of the article "how to use Spring features to implement multi-class dynamic calls of interfaces". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.