使用@PostConstruct创建需要依赖注入的工具类

现在某个需求要让我们创建一个工具类,但是它需要调用手Spring容器中的bean的方法。

我们知道,工具类的方法一般是静态方法或者是静态对象的方法。可是静态方法或者静态类方法初始化始终在spring依赖注入之前的。所以我们需要借助一个注解@PostConstruct,这个注解的解释是这个样子的:

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection. The method annotated with PostConstruct MUST be invoked even if the class does not request any resources to be injected. Only one method can be annotated with this annotation. The method on which the PostConstruct annotation is applied MUST fulfill all of the following criteria:

  • The method MUST NOT have any parameters except in the case of interceptors in which case it takes an InvocationContext object as defined by the Interceptors specification.
  • The method defined on an interceptor class MUST HAVE one of the following signatures:
    void (InvocationContext)
    Object (InvocationContext) throws Exception
    Note: A PostConstruct interceptor method must not throw application exceptions, but it may be declared to throw checked exceptions including the java.lang.Exception if the same interceptor method interposes on business or timeout methods in addition to lifecycle events. If a PostConstruct interceptor method returns a value, it is ignored by the container.
  • The method defined on a non-interceptor class MUST HAVE the following signature:
    void ()
  • The method on which PostConstruct is applied MAY be public, protected, package private or private.
  • The method MUST NOT be static except for the application client.
  • The method MAY be final.
  • If the method throws an unchecked exception the class MUST NOT be put into service except in the case of EJBs where the EJB can handle exceptions and even recover from them.

大家自行翻译,大致意思呢就是给一个无参的方法用了,spring容器会在依赖注入完成后并在方法所在的类投入使用之前执行这个方法。

下面做一个示例:

/**
 * 需要注入service的工具类
 *
 * @author yangbiao
 * @date 2021/1/8 16:22
 */

@Slf4j
@Component
public class ServiceUtil {
    private UserService userService;

    /**
     * 使用setter注入
     */
    @Autowired
    private void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 创建一个自身实例的静态常量
     */
    private static final ServiceUtil INSTANCE = new ServiceUtil();

    private ServiceUtil() {
        //无参构造器,防止他人实例化
    }

    /**
     * spring依赖注入完成后执行该方法
     */
    @PostConstruct
    public void init() {
        log.info("----init()前INSTANCE的userService={}", INSTANCE.userService);
        INSTANCE.setUserService(this.userService);
        log.info("----init()后INSTANCE的userService={}", INSTANCE.userService);
    }

    /**
     * 工具类静态方法,调用其他bean的方法
     */
    public static void doSome() {
        log.info("----doSome()---{}", INSTANCE.userService.listUserAll());
    }

}

在工具类中创建一个工具类常量实例。那么在spring依赖注入完成后(当然这个工具类也成spring管理的bean了,记为A)会执行这里的init()方法。会给INSTANCEuserServiceAuserService
那么静态方法调用userService就直接调用INTANCEuserService即可。
做个测试:

@SpringBootTest(classes = DemoApp.class)
class ServiceUtilTest {

    @Test
    void doSome() {
        ServiceUtil.doSome();
    }
}

结果:
在这里插入图片描述
工具类就能调用bean的方法了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值