在使用来自@Autowired
的注释@Value
和spring
注释时,如何订购成员变量字段?
您会将以下示例视为最佳做法吗?
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;
}
答案 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();
}
}