在 Java 中使用带有 CrossOrigin Annotation 或 Spring-Config XML 的 Spring 属性 [英] Use Spring Properties in Java with CrossOrigin Annotation or in Spring-Config XML
问题描述
我在 Spring 中使用 CrossOrigin 注释.现在我想注入一个属性作为注释的值.我不明白这个工作.
I use the CrossOrigin annotation in Spring. Now i want to inject a Property as value to the annotation. I dont get this to work.
现在我像这样访问我的财产:
Now i access my property like this:
@Value("${settings.cors_origin}")
String cors_origin;
我想将此属性注入到 CrossOrigin 注释中:
I want to inject this property to the CrossOrigin annotation:
....
@CrossOrigin(origins = cors_origin)
@RequestMapping(value="/request", method= RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getMethod()
{
...
我已经尝试过这样的事情:
I tried already something like this:
@CrossOrigin(origins = "${settings.cors_origin}")
编辑 1:
现在我尝试在我的 spring 配置中全局设置 CORS-Header:
Now i try to set the CORS-Header Globally in my spring config:
<context:property-placeholder location="classpath*:*appsettings.properties"/>
<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="${test}"
allowed-methods="GET, PUT, OPTIONS, POST"/>
</mvc:cors>
这个设置也不起作用!允许的来源与属性文件中指定的来源不同.我认为它不会将变量转换为值?当我在 spring 配置 allowed-origins 中手动设置 IP 地址时,它正在工作.设置有问题...
This setting is also not working! The allowed origin is not the same as the one specified in the properties file. I think it will not translate the variable to the value? When i set the IP-Address in the spring config allowed-origins manually it is working. There is something wrong with the settings...
appsettings.properties:
test=http://192.168.1.200
编辑 2:
S O L V E D
经过一段时间的故障排除后,我现在为我解决了:-)现在我再次使用注释@CrossOrigin.我必须将 RequestMethod Options 添加到 Spring RequestMapping:
I solved it for me now after a hart time of troubleshooting :-) Now i work again with the annotation @CrossOrigin. I had to add the RequestMethod Options to the Spring RequestMapping:
@RestController
@CrossOrigin(origins = {"${settings.cors_origin}"})
@RequestMapping("/api/v1")
public class MainController {
@RequestMapping(value="/request", method = {RequestMethod.GET, RequestMethod.OPTIONS}, produces = "application/json")
public ResponseEntity<?> getMethod()
{
感谢您的帮助!
推荐答案
您需要将字符串数组传递给 @CrossOrigin
注释的 origins
参数.这是用花括号完成的:
you need to pass an array of strings to the origins
argument of the @CrossOrigin
annotation. This is done with curly braces:
@CrossOrigin(origins = {"${settings.cors_origin}"})
然后在 Spring 中,src/main/resources/application.properties:
Then in Spring, src/main/resources/application.properties:
settings.cors_origin:http://localhost:4200
注意,不要在 application.properties 中的键值对右侧包含注释或额外空格.值后面的多余空格可能会导致键值对读取错误.
Note, don't include comments or extra spaces to the right of the key-value pair in application.properties. The extra spaces after the value might cause the key-value pair to be read incorrectly.
这篇关于在 Java 中使用带有 CrossOrigin Annotation 或 Spring-Config XML 的 Spring 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!