2

I have an entity with a created by field and I need to populate this field using the AuthenticatedUserService that I created. I need to inject this service in the entity such that I can generate the value for the created by field.

This is my Authenticated User Service

@Singleton
public class AuthenticatedUserService {

@Inject
private SecurityService securityService;

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

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

And I tried injecting the service in an entity using @Transient. But this returns NullPointerException for the instance of AuthenticatedUserService. The entity looks like this.

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

@Transient
@Inject
AuthenticatedUserService authenticatedUserService;

...  

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

Is there a way I can use the AuthenticatedUserService inside classes that aren't managed by the Micronaut?

I wish to do something like this but in Micronaut.

  • I don't know Micronaut but this is usually not possible because the Entitiy is not a managed class of the dependency injection framework. This is managed by Hibernate – Simon Martinelli Apr 16 '20 at 16:21
  • Thank you for your response, I'll edit my question accordingly to identify a way to use a bean managed by the Micronaut inside classes that are beyond its scope. – Shraday Shakya Apr 16 '20 at 16:53

1 Answers1

2

So, I found a way to do this. We need the instance of ApplicationContext to do this

public class ApplicationEntryPoint {

public static ApplicationContext context;

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

Then I created a utility that extracts beans from the ApplicationContext

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

Finally, extracted the bean of AuthenticatedUserService in the Entity using theBeanUtil.

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

...  

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