@PostConstruct使用

简介: @PostConstruct使用

在项目中我们可以使用@PostConstruct去初始化一些操作

例如

package com.ruben;
import com.ruben.dao.MpUserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@SpringBootTest
class SimpleSpringbootApplicationTests {
    private String name;
    @PostConstruct
    public void init() {
        name = "ruben";
    }
    @Test
    void test() {
        System.out.println(name);
    }
}

被@PostConstruct注解的方法,只会在服务器初始化的时候执行一次,也可以用于把spring容器中的bean置换出来成静态变量

package com.ruben;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruben.dao.MpUserMapper;
import com.ruben.pojo.dataObject.UserDataObject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
@SpringBootTest
class SimpleSpringbootApplicationTests {
    private String name;
    @Resource
    private MpUserMapper mpUserMapper;
    private static MpUserMapper staticMpUserMapper;
    @PostConstruct
    public void init() {
        name = "achao";
        staticMpUserMapper = mpUserMapper;
    }
    @Test
    void test() {
        System.out.println(name);
        List<UserDataObject> users = selectList(name);
        users.forEach(System.out::println);
    }
    public static List<UserDataObject> selectList(String name) {
        return staticMpUserMapper.selectList(Wrappers.lambdaQuery(UserDataObject.builder().build()).eq(UserDataObject::getUsername, name));
    }
}

打印结果

相关文章
|
人工智能 监控 Java
零代码改造 + 全链路追踪!Spring AI 最新可观测性详细解读
Spring AI Alibaba 通过集成 OpenTelemetry 实现可观测性,支持框架原生和无侵入探针两种方式。原生方案依赖 Micrometer 自动埋点,适用于快速接入;无侵入探针基于 LoongSuite 商业版,无需修改代码即可采集标准 OTLP 数据,解决了原生方案扩展性差、调用链易断链等问题。未来将开源无侵入探针方案,整合至 AgentScope Studio,并进一步增强多 Agent 场景下的观测能力。
3647 104
|
Java 应用服务中间件 AHAS
快速体验 Sentinel 集群限流功能,只需简单几步
️ Pic by Alibaba Tech on Facebook 集群限流 可以限制某个资源调用在集群内的总 QPS,并且可以解决单机流量不均导致总的流控效果不佳的问题,是保障服务稳定性的利器。 Sentinel 从 1.4.0 版本开始提供集群流控特性,但使用 Sentinel 集群限流需要对一系列的动态数据源进行相关配置,并且需要对开源控制台进行一些改造,有一定的使用成本。
16750 122
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8076 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10216 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1533 5
|
9天前
|
云安全 数据采集 人工智能