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.
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();
}
}