bean 中使用属性占位符${}的问题

提示:由于作者水平和时间有限,请仅以参考的态度阅读。

最近在读spring mvc 的官方文档,读到Controller 的时候,发现官方文档中,文档中如下片段:

URI path patterns can also have embedded ${…​} placeholders that are resolved on startup by using PropertyPlaceHolderConfigureragainst local, system, environment, and other property sources. You can use this, for example, to parameterize a base URL based on some external configuration.

写的是可以在URI patterns 中使用属性占位符${},于是刚兴趣想动手试试。
文档中明确的是占位符${}应该同PropertyPlaceHolderConfigurer一起使用,但是在实际开发过程中,发现并不能正确使用,参考了很多网上资料也没有解决,直到看到了Spring javaConfig编程式 配置properties属性@Value注入,博客中说道:

如果想用@Value("${app.name}") 这种占位符的方式。我们必须要配置一个PropertyPlaceholderConfigurer
PropertySourcesPlaceholderConfigurer。从Spring 3.1开始,推荐使PropertySourcesPlaceholderConfigurer,因为它能够基于Spring Environment及其属性源来解析占位符。如下的@Bean方法在Java中配置了PropertySourcesPlaceholderConfigurer

发现换成PropertySourcesPlaceholderConfigurer之后才管用,下面是测试的结果
于是想着自己动手试一试,就参照网上的,写了下面的代码:

  1. applicaiton.properties代码
user.path=user
  1. Controller
@Controller
public class UserController {
    @Value("${user.path}")
    String value;
    
    @GetMapping("/testUrlPlaceholder")
    public String getsValue() {
        return value;
    }

    @GetMapping("/${user.path}/{name}")
    public User getUser(@PathVariable("name") String name) {
        return new User(name, 10);
    }

    @GetMapping("/userReponsbody/{name}")
//    @ResponseBody
    public User getUer(@PathVariable("name") String name) {
        return new User(name, 40);
    }

}
  1. 首先是没有配置任何configuer的情况,这种直接报错。
@Configuration
@EnableWebMvc
@PropertySource("classpath:application.properties")
public class MyMvcConfiguration implements WebMvcConfigurer {
	//内容协商
	 @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .favorParameter(true)
                .parameterName("mediatype")
                .ignoreAcceptHeader(true)
                .favorPathExtension(true);

    }
	//视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/jsp/", ".jsp");
        registry.enableContentNegotiation(new MappingJackson2JsonView(), new MappingJackson2XmlView());
    }
}

测试http://localhost:8080/user/curry.json,得到的结果是:

{"user":{"name":"fuck","age":10}}
  1. 如果配置文档中描述的PropertyPlaceHolderConfigurer:
@Configuration
@EnableWebMvc
@PropertySource("classpath:application.properties")
public class MyMvcConfiguration implements WebMvcConfigurer {
	//内容协商
	 @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .favorParameter(true)
                .parameterName("mediatype")
                .ignoreAcceptHeader(true)
                .favorPathExtension(true);

    }
	//视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/jsp/", ".jsp");
        registry.enableContentNegotiation(new MappingJackson2JsonView(), new MappingJackson2XmlView());
    }
@Bean
    public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(){
        return new PropertyPlaceholderConfigurer();
    }
}

测试http://localhost:8080/user/curry.json, 则直接报错

java.lang.IllegalArgumentException: Could not resolve placeholder ‘user.path’ in value “${user.path}”

  1. 配置 PropertySourcesPlaceholderConfigurer
@Configuration
@EnableWebMvc
@PropertySource("classpath:application.properties")
public class MyMvcConfiguration implements WebMvcConfigurer {
	//内容协商
	 @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .favorParameter(true)
                .parameterName("mediatype")
                .ignoreAcceptHeader(true)
                .favorPathExtension(true);

    }
	//视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/jsp/", ".jsp");
        registry.enableContentNegotiation(new MappingJackson2JsonView(), new MappingJackson2XmlView());
    }
  @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

结果正常输出。

总结:

如果在bean中想使用属性占位符,或者想通过@value("${}"),可以不做配置,或者配置propertySourcesPlaceholderConfigurer,不能配置PropertyPlaceholderConfigurer

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值