代码质量 - @Autowired成员变量的顺序?

时间:2015-05-12 07:45:31

标签: java spring code-conversion

在使用来自@Autowired的注释@Valuespring注释时,如何订购成员变量字段?

您会将以下示例视为最佳做法吗?

public class MyExample {
    private static final Logger logger;
    private static final int STATIC_VAR = 1;

    @Autowired
    private WebService service;

    @Value("${my.property}")
    private String property;

    //to be set by setter or constructor
    private MailService mail;
}

1 个答案:

答案 0 :(得分:1)

我不确定实例成员的顺序真的很重要。也就是说,我喜欢通过构造函数设置它们,以便它们可以是最终的:

public class MyExample {

  private static final Logger logger;
  private static final int STATIC_VAR = 1;

  private final WebService service;

  private final String property;

  private final MailService mail;

  @Autowired
  public MyExample(WebService service, @Value("${my.property}") String property) {
    this.service = service;
    this.property = property;
    mail = new MailService();
  }

}