一个神奇的标签-@PostConstruct

1、问题描述

项目中封装了个restTemplate的静态调用类,统一调用外围接口,但是发现外围系统有些接口反应时间不稳定,还存在失败的情况,为了便于追踪问题,将对外围系统的入参和出参以及响应时间写入到数据库中,但是项目中都是通过静态类调用的,写入数据的方法是动态方法,无法使用,记录下解决方案,希望能帮助需要的朋友。

2、解决方案

2.1 简单介绍

简单说就是用使用jdk提供的@PostConstruct这个标签来实现,先介绍下@PostConstruct这个神奇的标签。

Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

重点说下执行顺序:

通常我们会是在Spring框架中使用到@PostConstruct注解,该注解的方法在整个Bean初始化中的执行顺序:

Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

这个顺序很重要,这样我们就可以利用@Autowired注入的bean了。

2.2 代码介绍

package com.laowang.spcrud.service;

import com.laowang.spcrud.db.entity.LPageInfo;
import com.laowang.spcrud.db.entity.TLaowang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
/**
 * 软件老王静态调用service测试类
 */
@Component
public class StatisTest {

    public static StatisTest statisTest = new StatisTest(); //声明对象

    //Spring注入
    @Autowired
    TestService testService;

    //初始化
    @PostConstruct
    public void init() {
        statisTest.testService = testService;
    }

    public static void staticPrint() {
        System.out.println("软件老王是个大帅哥!");
    }

    public static void testMain() {
        StatisTest.staticPrint();
        
        List<TLaowang> list = statisTest.testService.selectAll(new LPageInfo(1, 2));
        System.out.println(list.toString());
    }
}

通过以上代码可以看出来主要是以下三行代码:

(1)new 一个静态对象,这个时候对象里面的testService是空值

public static StatisTest statisTest = new StatisTest(); //声明对象

(2)spring通过标签@Autowired注入servicebean

  @Autowired
  TestService testService;

(3)通过 @PostConstruct,将Spring注入的bean赋给new出来的StatisTest对象的testService

    //初始化
    @PostConstruct
    public void init() {
        statisTest.testService = testService;
    }

2.3 项目启动

当项目启动的时候,这个时候进入@PostConstruct的init方法的时候,发现statisTest对象的service是空的, 通过spring标签@Autowired注入的TestService(bean),已经有值;

2.4 代码验证

2.4.1 controller中直接通过类.方法调用

    @RequestMapping(value ="/test", method = RequestMethod.POST)
    @ResponseBody
    public  void test() {
        StatisTest.testMain();
    }

2.4.2 swagger验证

2.4.3 进入testmain方法

2.4.4 数据已经从数据库中获取到


更多信息请关注公众号:「软件老王」,关注不迷路,软件老王和他的IT朋友们,分享一些他们的技术见解和生活故事。

posted @ 2021-08-08 21:46  软件老王  阅读(161)  评论(0编辑  收藏  举报