Spring:在实例化最终字段的自动装配构造函数中使用application属性

时间:2017-06-10 02:10:17

标签: java spring spring-mvc spring-boot dependency-injection

我已在下面创建了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

我的问题是:

  1. 为什么服务没有按预期工作?
  2. 考虑到我希望uglyChar在单身人士服务中成为最终来自application.properties
  3. 是什么才是正确的方法?

    注意:如果我将String.valueOf(uglyChar)替换为String.valueOf(uglyCharFromAppProp),服务就会开始工作,但uglyChar不会是最终的,因为我希望它是

1 个答案:

答案 0 :(得分:3)

当实例化对象时,首先执行构造函数,然后设置属性的值并执行@Value。因此,uglyChar的值没有该属性的值。

你可以用:

   private final char uglyChar;

   @Autowired
   public UglifyServiceImpl(@Value("${ugly.char}") final char uglyCharFromAppProp){
       this.uglyChar = uglyCharFromAppProp;
   }