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.