【问题标题】:How to use beans inside classes that are not managed by the Micronaut?如何在不受 Micronaut 管理的类中使用 bean?
【发布时间】:2020-04-16 16:17:51
【问题描述】:

我有一个带有created by 字段的实体,我需要使用我创建的AuthenticatedUserService 填充此字段。我需要在实体中注入此服务,以便为created by 字段生成值。

这是我的认证用户服务

@Singleton
public class AuthenticatedUserService {

@Inject
private SecurityService securityService;

public String getUserIdentifier() {
    var authentication = securityService.getAuthentication();

    return String.valueOf(authentication.get().getAttributes().get("identifier"));
}

我尝试使用@Transient 在实体中注入服务。但这会为 AuthenticatedUserService 的实例返回 NullPointerException。实体看起来像这样。

@Entity(name = "car")
public class Car {
...
private String createdBy;

@Transient
@Inject
AuthenticatedUserService authenticatedUserService;

...  

 @PrePersist
 public void prePersist() {
    this.createdBy = authenticatedUserService.getUserIdentifier();
 }
}

有没有办法可以在不由 Micronaut 管理的类中使用 AuthenticatedUserService?

我希望在 Micronaut 中做类似 this 的事情。

【问题讨论】:

  • 我不知道 Micronaut 但这通常是不可能的,因为实体不是依赖注入框架的托管类。这是由 Hibernate 管理的
  • 感谢您的回复,我将相应地编辑我的问题,以确定在超出其范围的类中使用由 Micronaut 管理的 bean 的方法。

标签: java hibernate micronaut micronaut-data


【解决方案1】:

所以,我找到了一种方法来做到这一点。我们需要ApplicationContext 的实例来做到这一点

public class ApplicationEntryPoint {

public static ApplicationContext context;

public static void main(String[] args) {
    context = Micronaut.run();
 }
}

然后我创建了一个从 ApplicationContext 中提取 bean 的实用程序

public class BeanUtil{
 public static <T> T getBean(Class<T> beanClass) {
    return EntryPoint.context.getBean(beanClass);
 }
}

最后,使用BeanUtil提取Entity中AuthenticatedUserService的bean。

@Entity(name = "car")
public class Car {
...
private String createdBy;

...  

 @PrePersist
 public void prePersist() {
 var authenticatedUserService = BeanUtil.getBean(AuthenticatedUserService.class);
  this.createdBy = authenticatedUserService.getUserIdentifier();
 }
}

【讨论】:

  • 运行测试时上下文是否可用?
猜你喜欢
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多