package com.ruoyi.buss.controller; import com.ruoyi.buss.common.dynamic.DynamicBeanRegistrar; import eu.bitwalker.useragentutils.Application; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.web.bind.annotation.*; import java.lang.reflect.Method; @Tag(name = "代码加载测试") @RestController @RequestMapping("/dynamic") public class DemoController { private final DynamicBeanRegistrar registrar; public DemoController(ApplicationContext context) { this.registrar = new DynamicBeanRegistrar((ConfigurableApplicationContext) context); } @Autowired private ApplicationContext applicationContext; @Operation(summary = "动态代码加载测试") @GetMapping("/compile") @ResponseBody public String compile(@RequestParam("code") String code) throws Exception { String sourceCode = "public class Demo { public String test(String code) { return \"Hello\" + code; } }"; String className = "DynamicService_" + System.currentTimeMillis(); registrar.registerBean(className.toLowerCase(), "Demo", sourceCode); System.out.println("Compiled:" + className); Object bean = applicationContext.getBean(className); Method method = bean.getClass().getMethod("test"); Object object = method.invoke(code); System.out.println(object.toString()); return "Compiled: " + className; } }