Created
July 22, 2023 14:02
-
-
Save joshlong/62e4fe840508a7812f34a5288bf71853 to your computer and use it in GitHub Desktop.
AOT for Spring ViewComponents with Thomas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
class VcConfiguration { | |
@Bean | |
static ViewComponentResourceAotProcessor viewComponentResourceAotProcessor() { | |
return new ViewComponentResourceAotProcessor(); | |
} | |
} | |
class ViewComponentResourceAotProcessor implements BeanRegistrationAotProcessor { | |
// todo share this logic with the AOP aspect | |
private static Resource viewComponentTemplateResourceFor(Class<?> clzz) { | |
var name = '/' + clzz.getPackage().getName().replace(".", "/") + '/' + clzz.getSimpleName() + ".html"; | |
return new ClassPathResource(name); | |
} | |
@Override | |
public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { | |
var clzz = registeredBean.getBeanClass(); | |
var isViewComponent = MergedAnnotations.from(clzz).isPresent(ViewComponent.class); | |
if (isViewComponent) { | |
return (generationContext, beanRegistrationCode) -> { | |
var resource = viewComponentTemplateResourceFor(clzz); | |
Assert.state(resource.exists(), "the resource for the @ViewComponent class %s could not be found!".formatted(clzz.getName())); | |
generationContext.getRuntimeHints().resources().registerResource(resource); | |
}; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment