这就是我想要做的:
@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
使用基于命令行参数的值。该怎么办?
答案 0 :(得分:0)
在第一个请求中。 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之后,您的动态网址将进入handdlerMapping。
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