
在 Symfony 5.4 + ApiPlatform 环境中,自定义 Entity 无法出现在 Swagger UI 文档页面,通常是因使用了已废弃的注解命名空间 ApiPlatform\Core\Annotation\ApiResource,需升级为 ApiPlatform\Metadata\ApiResource。
在 symfony 5.4 + apiplatform 环境中,自定义 entity 无法出现在 swagger ui 文档页面,通常是因使用了已废弃的注解命名空间 `apiplatform\core\annotation\apiresource`,需升级为 `apiplatform\metadata\apiresource`。
ApiPlatform 自 3.0 版本起全面迁移至新的元数据系统(ApiPlatform\Metadata),旧版 ApiPlatform\Core\Annotation 已被弃用且不再被自动识别。即使你已正确添加 @ApiResource()、清除缓存(bin/console cache:clear)并重启开发服务器,若注解导入路径错误,该实体仍不会被 API Platform 扫描和注册,导致其完全不出现在 OpenAPI 文档(Swagger UI)中。
✅ 正确做法是更新命名空间导入:
// api/src/Entity/Review.php
<?php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource; // ✅ 替换为新命名空间
use Doctrine\ORM\Mapping as ORM;
#[ApiResource] // 推荐使用 PHP 8+ 属性语法(Attribute)
class Review
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'integer')]
public int $rating = 0;
#[ORM\Column(type: 'text')]
public string $body = '';
#[ORM\Column(type: 'string', length: 255)]
public string $author = '';
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
public ?\DateTimeInterface $publicationDate = null;
#[ORM\ManyToOne(targetEntity: Book::class)]
public ?Book $book = null;
public function getId(): ?int
{
return $this->id;
}
}⚠️ 注意事项:
- 若项目仍在使用 PHP 必须使用 use ApiPlatform\Metadata\ApiResource;
- 确保实体类位于 src/Entity/(或 api/src/Entity/)且被 Doctrine 实体扫描器覆盖(检查 doctrine.orm.mappings 配置)
- 运行 bin/console debug:router | grep api 和 bin/console api:openapi:export 可验证实体是否已被注册
- 若依赖 Book 类,请确保 App\Entity\Book 同样使用 ApiPlatform\Metadata\ApiResource 并已正确定义
? 总结:从 ApiPlatform v3 开始,ApiResource 必须从 ApiPlatform\Metadata 导入;沿用旧命名空间将导致实体静默失效——这是新手最常见的“文档不显示”原因。升级后无需额外配置,刷新 Swagger UI 即可立即看到 /api/reviews 等端点。

















