I'm working on spring as part of my classwork and using Javapoet for code generation.
Is there a way I can create Spring Beans via JavaPoet?
I have a use case where I wish to create Java classes based on the configuration and load them up into spring context as beans.
I am aware I can use the @Profile to achieve the same, but I have been asked to do it via Javapoet because the annotation would be too easy.
Update - Here is my main class
package com.example.PhotoAppDiscoveryService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.javapoet.AnnotationSpec;
import org.springframework.javapoet.JavaFile;
import org.springframework.javapoet.MethodSpec;
import org.springframework.javapoet.TypeSpec;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.lang.model.element.Modifier;
import java.io.IOException;
import java.nio.file.Paths;
@SpringBootApplication
public class PhotoAppDiscoveryServiceApplication {
public static void main(String[] args) throws IOException {
generateRestController();
SpringApplication.run(PhotoAppDiscoveryServiceApplication.class, args);
}
private static void generateRestController() throws IOException {
MethodSpec main = MethodSpec.methodBuilder("getMapper")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(
AnnotationSpec.builder(RequestMapping.class)
.addMember("value", "$S", "/api")
.build()
)
.returns(String.class)
.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
.addStatement("return \"Response from Generated code!\"")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addAnnotation(RestController.class)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
JavaFile javaFile = JavaFile.builder("com.example.PhotoAppDiscoveryService", helloWorld)
.build();
javaFile.writeTo(System.out);
System.out.println("\n");
try {
javaFile.writeTo(Paths.get("src/main/java/"));
} catch (Exception e){
System.out.println("Exception occurred!");
e.printStackTrace();
}
}
}