如何注入@Configuration以在JPA @Entity中看到

问题描述 投票:0回答:1
src/main/resources/application.properties
cdn.url = http://foo.mycompany.com
cdn.prefix = reports

CDN配置

@Configuration
@ConfigurationProperties(prefix = "cdn")
@ConfigurationPropertiesScan
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CDNConfig {
    private String url;
    private String prefix;
}

CDN JPA 实体。我想将在加载时填充到 JPA 实体中的 CDNConfig 的值注入,但我无法以正确的方式执行此操作。如何将 CDNConfig 中的值引入 CDN.java 以便我可以使用 CDN 配置值?

我尝试将 CDNConfig 表示为组件,但没有成功。 我在JPA实体中尝试了CDNConfig的@Autowired,它也不起作用。

@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "cdn")
public class CDN {

    @Transient
    private CDNConfig cdnConfig; 

}
spring spring-boot
1个回答
0
投票

CDN
不是一个 bean => 不保存在 Spring 容器中 =>
@Autowired
不起作用。此外,基于方法的构造函数注入也将无法正常工作。

您需要通过构造函数传递

CDNConfig

...
public class CDN {

  // ...

  @Transient
  private CDNConfig cdnConfig;

  public CDN(CDNConfig cdnConfig) {
    this.url = cdnConfig.getUrl();
  }

  // ...
}

在创建新

CDN
的代码中,您需要提取
CDNConfig
并将其传递给构造函数:

...
CDNConfig cdnConfig = applicationContext.getBean(CDNConfig.class);
CDN cdn = new CDN(cdnConfig);
...

这不是最好的解决方案并以另一种方式编写代码,但如果您需要,它会起作用🙂


在这种情况下,您也可以执行

private CDNConfig cdnConfig
作为
final
字段:

private final CDNConfig cdnConfig; 
© www.soinside.com 2019 - 2024. All rights reserved.