Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Spring implements the tool class injection Service method through annotations

Shulou Source: shulou.com Published: 2022-06-03 05:25:02 10月03日 Update

In the process of development, we often come across tool classes, in order to perform CRUD operations, we need to call the Service implementation class, which can be obtained by the following methods. Method 1 [tedious, internal static] 1injection @ Component

In the persistence layer, business layer, and control layer, @ Repository, @ Service, and @ Controller are used to stare at the classes in the hierarchy, while @ Component is used to stare at the more neutral classes.

[as shown below: @ Repository and @ Service,@Controller,@Component gaze at different types of classes under the same path]

2injection @ PostConstruct

The actions taken before initializing and destroying the bean are implemented through the @ PostConstruct and @ PreDestroy methods.

Define a utility class parameter for static through step 1, and instantiate the static parameter in initialization with @ PostConstruct in step 2

```@ Componentpublic class SMSUtils {@ Autowiredprivate ISmsService smsService; / / add private members of the required service [cannot add static, otherwise smsService will be equal to null, because the static method is a method that is loaded before the object is created, is executed before the construction, and belongs to the class] private static SMSUtils smsUtils; / / step 1 statically initializes a utility class in order to public static final String SMS_PHONE_CODE = "xxxxx" before the initialization of the spring Public static final String SMS_REG_SUCCESS = "yyyyyy"; @ PostConstructpublic void init () {smsUtils = this; smsUtils.smsService = this.smsService / / step 2 instantiate the statically instantiated testService when initializing, that is, you can use smsUtils.smsService.smsServicelai to call the service service} / / send SMS verification code params. Please public static void sendSms (String phone, String [] params, String templateCode) {SmsResponse smsResponse = smsUtils.smsService.sendSms (phone, jsonStr, templateCode) in strict order according to the output fields of the template. Method 2 [leave it to spring, recommended] step 1 injection @ Component, the tool class has been injection to spring step 2 bet on the tool class @ Autowired@Componentpublic class SMSUtils {@ Autowired private ISmsService smsService;.} @ RestControllerpublic class AuthController extends SuperRestController {@ Autowired private SMSUtils smsUtils;....

Tags: Tools steps methods static parameters instances ways different tedious business strictly according to can be passed fields objects members templates text messages types paths Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Xiaomi Shulou Technology Linux MariaDB