spring boot - Java - Implement @Component class dynmically - Stack Overflow

时间: 2025-01-06 admin 业界

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

}