# @PostConstruct 注解构建错误

**URL:** <https://www.isharkfly.com/t/postconstruct/16176>\
**Category:** 程序语言\
**Tags:** java\
**Created:** [August 21, 2024, 6:04pm UTC](https://www.isharkfly.com/t/postconstruct/16176 "2024-08-21T18:04:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [August 21, 2024, 6:04pm UTC](https://www.isharkfly.com/t/postconstruct/16176/1 "2024-08-21T18:04:43Z")

</div>

最近在一个老的 Java 项目中，构建出现了 ： `@PostConstruct` 注解无法编译的错误。

 ![2025-04-17_14-10-47](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/3X/d/0/d043353a0215b2c5099622fc55a1b5c8e4fb60ab.jpeg)

@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。

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

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

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

实战：在静态方法中调用依赖注入的Bean中的方法。

如果想在生成对象时完成某些初始化操作，而偏偏这些初始化操作又依赖于依赖注入，那么久无法在构造函数中实现。

为此，可以使用@PostConstruct注解一个方法来完成初始化，@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

- 因为当调用构造函数时，bean还没有初始化-即没有注入依赖项。在`@PostConstruct`方法完全初始化bean，您可以使用依赖项。
- 因为这是保证在bean生命周期中只调用一次此方法的契约。一个bean可能会在其内部工作过程中被容器多次实例化(虽然不太可能)，但它保证`@PostConstruct`只会被调用一次。

---

<div class="post-metadata">

**Author:** ![hex](https://www.isharkfly.com/user_avatar/www.isharkfly.com/hex/32/21953_2.png) [@hex](https://www.isharkfly.com/u/hex)\
**Post date:** [August 21, 2024, 6:04pm UTC](https://www.isharkfly.com/t/postconstruct/16176/2 "2024-08-21T18:04:45Z")

</div>

具体，出现上面问题的原因是 JDK 的版本。

对老项目我们使用了 JDK 17 的版本进行编译，这个版本实在是太高了。

所以需要加入下面的依赖才行。

```auto
       <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency

```

对不少的老项目，实在没有办法就需要把一些老的依赖给添加进来。

 ![2025-04-17_14-13-55](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/3X/a/8/a817adf41a8774faf90bf9aeb25be8aa3a0e3eee.jpeg)

为了避免上面的问题持续出现，还是需要尽快升级。

---

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [April 17, 2025, 6:08pm UTC](https://www.isharkfly.com/t/postconstruct/16176/3 "2025-04-17T18:08:42Z")

</div>

Made this topic public on April 17, 2025, 6:08pm UTC


