spring boot - Java - Implement @Component class dynmically - Stack Overflow
I have the following jave interface
import org.springframework.stereotype.Repository;
@Repository
public interface ITest {
void testFunc();
}
And I am using the interface in my controller
@RestController()
@CrossOrigin(origins = "*")
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private ITest iTest;
@GetMapping()
public List<User> test() {
return this.userService.getUsers();
}
@GetMapping("/test")
public String ttest() {
iTest.testFunc();
return "Hello World!";
}
}
When I manually add the interface implementation everything works fine But I want to add the implementation at runtime based on specific configuration. This is what i tried to do but it didn't work, is there something missing?
@SpringBootApplication
public class EcommerceApplication {
public static void main(String[] args) throws IOException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
String s = "package com.justtech.ecommerce.db;\n" +
"\n" +
"import org.springframework.stereotype.Component;\n" +
"\n" +
"@Component\n" +
"public class Test2 implements ITest {\n" +
"\n" +
"\n" +
" @Override\n" +
" public void testFunc() {\n" +
" System.err.println(\"Hello World\");\n" +
" }\n" +
"}\n";
dynamicClass(s, "com.justtech.ecommerce.db.Test2", "Test2");
SpringApplication.run(EcommerceApplication.class, args);
}
static void dynamicClass(String sourceCode, String className, String fileName) throws IOException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
System.err.println(System.getProperty("user.dir"));
File parent = new File(System.getProperty("user.dir"));
File sourceFile = new File(parent, fileName + ".java");
sourceFile.deleteOnExit();
FileWriter writer = new FileWriter(sourceFile);
writer.write(sourceCode);
writer.close();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null, null, null);
File parentDir = sourceFile.getParentFile();
standardJavaFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(parentDir));
Iterable<? extends JavaFileObject> compilationUnits = standardJavaFileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
javaCompiler.getTask(null, standardJavaFileManager, null, null, null, compilationUnits).call();
standardJavaFileManager.close();
URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[]{parentDir.toURI().toURL()});
Class<?> dynamicClass = urlClassLoader.loadClass(className);
// Method formula1 = dynamicClass.getDeclaredMethod("formula1");
// formula1.invoke(dynamicClass.newInstance());
}
}
最新文章
- Intel兵屯深圳,意欲何为?
- 百度部分下线盗版视频 反盗版方敦促其全面停止
- 全球PC销量创五年新低 硬件式微应用崛起
- 力压谷歌、苹果,微软凭什么成为软件霸主?
- 2012年NEC云时代平台软件全国巡展启动
- 2020年或诞生超级计算机:相当5000万台笔记本
- Why does this typecheck in Lean? - Stack Overflow
- opengl - How to render a FBO into an ImGui window? - Stack Overflow
- node.js - Mongoose schema worked with the main db but not with test db - Stack Overflow
- google colaboratory - Load a Kaggle dataset into Colab notebook without extracting it - Stack Overflow
- python - Filtering from index and comparing row value with all values in column - Stack Overflow
- c++ - Wrong Precision Results with std::ostringstream - Stack Overflow
- javascript - How to properly handle AES encryption in React Native and generate Random Key for AES encryption? - Stack Overflow
- angular - How to resolve vitest errors; stylesheet imports and dynamically fetched modules - Stack Overflow
- python - overrideredirect() no longer working on MAC? - Stack Overflow
- javascript - useState rerenders bindings increment when key added to object but not removed - Stack Overflow
- tsconfig - Is there a typescript compiler option that prevents implicit widening from readonly properties to readwrite? - Stack