gpt4 book ai didi

java - Spring 启动: How to pass a command line argument into an annotation value?

转载 作者:行者123 更新时间:2023-12-02 04:53:54 25 4
gpt4 key购买 nike

这是我正在尝试做的事情:

@SpringBootApplication public class App {
public static final String NAME;

public static void main(String[] args) {
SpringApplication.run(App.class, args);
}

@Autowired public App(ApplicationArguments arguments) {
NAME = arguments.getSourceArgs()[0]; // ERROR (1)
}

@GetMapping("/" + NAME) public void test() { // ERROR (2)
return NAME;
}
}

该代码无法按编写的方式工作,因为 (1) 无法分配 NAME,并且 (2) @GetMapping 的注释值必须是常量表达式。

我只想@GetMapping 使用基于命令行参数的值。如何做到这一点?

最佳答案

在第一个请求中。 spring mvc 将初始化资源。所以你把你的动态网址放在haddlermapping中。

我们需要三个类。 MyController MyDispatcherServlet DispatcherServletCustomConfiguration

MyController.java

@Component(value="MyController")
public class MyController {

@Autowired
ClaimService claimService;

public ResponseEntity<HttpStatus> insertClaim() {
return new ResponseEntity<>(HttpStatus.OK);
}

}

MyDispatcherServlet.java。在 initStrategies.put 之后,将您的动态 url 放入 handlerMapping 中。

public class MyDispatcherServlet extends DispatcherServlet {

private String url;


public MyDispatcherServlet(String url) {
super();
this.url = url;
}


@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
List<HandlerMapping> handlerMappings = getHandlerMappings();
for (HandlerMapping handlerMapping : handlerMappings) {

if (handlerMapping instanceof RequestMappingHandlerMapping) {
RequestMappingHandlerMapping requestMappingHandlerMapping = ((RequestMappingHandlerMapping) handlerMapping);
RequestMappingInfo.Builder n = RequestMappingInfo
.paths(url)
.methods(RequestMethod.GET);
try {
Method method = MyController.class.getDeclaredMethod("insertClaim");
requestMappingHandlerMapping.registerMapping(n.build(), "MyController", method);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}

}
}

}


}

DispatcherServletCustomConfiguration.java

@Configuration
public class DispatcherServletCustomConfiguration {

@Value("${myUrl}")
private String url;

@Bean
public DispatcherServlet dispatcherServlet() {
return new MyDispatcherServlet(url);
}

}

使用命令java -jar stackoverflow-1.0-SNAPSHOT.jar --myUrl=abcd运行

关于java - Spring 启动: How to pass a command line argument into an annotation value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56419437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com