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

How does springboot dynamically call different implementation classes through different policies

2025-01-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Most people do not understand the knowledge points of this article "how springboot dynamically calls different implementation classes through different strategies", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how springboot dynamically calls different implementation classes through different strategies".

Dynamically call different implementation classes through different policies

We often encounter such a requirement that the entity type passed by the front end is the same, and the back end needs to dynamically call the method of a certain class according to a string in the entity class.

In SpringBoot, we can understand that a Controller interface corresponds to multiple ServiceImpl. In this way, if you need to add a function later, you can just create a ServiceImpl instead of creating an additional Controller interface.

Now suppose a scenario in which a different user type is passed in from the front end, and the back end returns the user's task.

You may ask me, why not just put (user type, user task) in the database?

Now it's just a simple scenario, but it's actually more complex and can't be directly stored in the database.

Code demonstration

Let's define an interface first.

Public interface UserService {/ / returns the user's main task String task ();}

Two implementation classes

@ Service ("student") public class StudentServiceImpl implements UserService {@ Override public String task () {return "learning";}} @ Service ("teacher") public class TeacherServiceImpl implements UserService {@ Override public String task () {return "teaching";}}

Core classes that implement dynamic invocation

@ Servicepublic class UserContext {@ Autowired Map userMap; public UserService getUserService (String type) {return userMap.get (type);}}

Spring automatically injects shapes such as (the name after @ Service, the class that implements the interface) into the userMap

After startup, there are two elements in the userMap, ("student", StudentServiceImpl) and ("teacher", TeacherServiceImpl)

The getUserService method returns the UserService object of key=type in userMap

Entity class

Public class User {private String type; private String task; public String getType () {return type;} public void setType (String type) {this.type = type;} public String getTask () {return task;} public void setTask (String task) {this.task = task;}}

Controller layer interface

@ RestController@RequestMapping ("/ user") public class UserController {@ Autowired UserContext userContext; @ PostMapping ("/ getTask") public String getTask (@ RequestBody User user) {UserService userService = userContext.getUserService (user.getType ()); return userService.task ();}}

Test sample:

Examples of scenarios that may be used

Dashboard statistics on inventory

The front end inputs information such as region id, warehouse id, item id, etc.

The backend dynamically selects an item implementation class according to the parameters, and finally returns the statistical information.

Here are a few questions, why not pass in the id of all items at once and get the inventory of all items at once?

Once input, the backend processing time may be long, and the failure rate is also high. In case of failure, the entire dashboard does not have any data. And later may face a demand, different items, need to have different interface refresh speed, the best-selling items interface call frequency is fast. So you may need to group items into groups, a group of the same type, using an implementation class.

For example, there are 100 items that are divided into 10 groups according to type or other attributes. Each group has a different attribute groupId, but the 10 groups share a common interface. After entering the interface, enter 10 different implementation classes, and call the specific computing logic in the implementation class.

Dynamic selection of implementation classes in spring

In spring, when an interface has multiple implementation classes, different interface implementation classes are obtained according to the different parameters passed in by creating a simple factory class.

Public interface ExecuteService {ExecuteEnum getCode (); / / Business method void execute ();} @ Servicepublic class FirstExecuteServiceImpl implements ExecuteService {@ Override public ExecuteEnum getCode () {return ExecuteEnum.FIRST;} public void execute () {System.out.println ("11111111111");} @ Servicepublic class SecondExecuteServiceImpl implements ExecuteService {@ Override public ExecuteEnum getCode () {return ExecuteEnum.SECOND } public void execute () {System.out.println ("222222222");}} public enum ExecuteEnum {FIRST, SECOND,;} scenario 1 @ Componentpublic class ExecuteServiceFactory implements ApplicationContextAware {private final static Map EXECUTE_SERVICES = new HashMap (); @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {Map types = applicationContext.getBeansOfType (ExecuteService.class) Types.values () .forEach (e-> EXECUTE_SERVICES.putIfAbsent (e.getCode (), e));}} scenario two @ Componentpublic class ExecuteServiceFactory implements InitializingBean {@ Autowired private List executeServices; public final static Map EXECUTE_SERVICES = new HashMap (); @ Override public void afterPropertiesSet () throws Exception {executeServices.forEach (l-> EXECUTE_SERVICES.putIfAbsent (l.getCode (), l)) }} the above is the content of this article on "how springboot dynamically invokes different implementation classes through different strategies". I believe everyone has a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about related knowledge, please follow 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: 287

*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

Development

Wechat

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

12
Report