我已在下面创建了MCVE。该服务应收到一条消息,并使用来自ugly.char
的预定义application.properties
替换元音。
application.properties:
ugly.char=x
UglifyService.java:
public interface UglifyService {
String uglifyMessage(String message);
}
UglifyServiceImpl.java:
@Service
public class UglifyServiceImpl implements UglifyService {
@Value("${ugly.char}")
private char uglyCharFromAppProp;
private final char uglyChar;
@Autowired
public UglifyServiceImpl() {
this.uglyChar = uglyCharFromAppProp;
}
@Override
public String uglifyMessage(String message) {
return message.replaceAll("[aeiouAEIOU]", String.valueOf(uglyChar));
}
}
UglyCharController.java:
@Controller
public class UglyCharController {
private final UglifyService uglifyService;
@Autowired
public UglyCharController(UglifyService uglifyService) {
this.uglifyService = uglifyService;
}
@Value("${ugly.char}")
private char uglyChar;
@RequestMapping("/")
@ResponseBody
public String index() {
return "Usage: http://localhost:8080/some-message";
}
@GetMapping("/{message:.+}")
@ResponseBody
public String uglifyMessage(@PathVariable String message) {
String uglyMessage = uglifyService.uglifyMessage(message);
return "The ugly char is: '"+ uglyChar +"'." +
"<br>The uglifyed message is: "+ uglyMessage;
}
}
Application.java:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
问题在于,服务只是删除它们而不是替换元音。
请求localhost:8080/mymessage
时,回复应为mymxssxgx
,但我收到mymssg
。
我的问题是:
uglyChar
在单身人士服务中成为最终来自application.properties
? 注意:如果我将String.valueOf(uglyChar)
替换为String.valueOf(uglyCharFromAppProp)
,服务就会开始工作,但uglyChar
不会是最终的,因为我希望它是
答案 0 :(得分:3)
当实例化对象时,首先执行构造函数,然后设置属性的值并执行@Value
。因此,uglyChar的值没有该属性的值。
你可以用:
private final char uglyChar;
@Autowired
public UglifyServiceImpl(@Value("${ugly.char}") final char uglyCharFromAppProp){
this.uglyChar = uglyCharFromAppProp;
}