Value注解的用法

我们上面的项目中访问的方式是通过实例化restTemplate的形式进行访问调用,那么我们如果有很多项目的时候,当某个服务的ip需要更换,我们就需要打开这个项目到具体的方法里面进行修改,这样形成了硬编码,不好修改,我们可以使用Value注解,将值放入配置中

#端点配置
server.port=8010

#项目配置说明,通过http://ip(localhost):端口(8010)/info进行查询
[email protected]@
info.app.encoding:@project.build.sourceEncoding@
info.app.java.source:@java.version@
info.app.java.target:@java.version@

#通过软编码,通过Value注解的形式获取配置中的值
user.userServiceURL=http://localhost:8000/

ConsumerController.java

package com.lyl.cloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.lyl.cloud.entity.User;

@RestController
public class ConsumerController {

	@Autowired
	private RestTemplate restTemplate;
	
	@Value("${user.userServiceURL}")
	private String userServiceUrl;
	
	@GetMapping("/user/{id}")
	public User findById(@PathVariable Long id) {
		return this.restTemplate.getForObject(this.userServiceUrl+id,User.class);
	}
}

启动两个项目,然后浏览器访问:

Value注解的用法_第1张图片

你可能感兴趣的:(Value注解的用法)