13693261870
2025-07-02 6708810c4de34dfb9513061432d656f91d56ee3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
    }
}