Intellij reordering code affects spring beans
已回答
Hi all,
having a simple spring project, I just wasted a good part of an hour looking for a 'bug'. It seems I hit the reformat code keyboard shortcut as I always do. This cleaned up the file I'm working on nicely, but moved Spring elements around. This messed up the execution order and as a result my application was failing. Something like the below:
@Value("${root:Base}")
public String root;
@Value("${stage:Alpha}")
private String stage;
@Value("${realm:someRealm}")
private String realm;
@Autowired
SomeClient csaClient;
became...
@Value("${root:Base}")
public String root;
@Autowired
SomeClient csaClient;
@Value("${stage:Alpha}")
private String stage;
@Value("${realm:someRealm}")
private String realm;
This caused the "SomeClient" to instantiate with "null" values for the two last variables.
Is Intellij not 'smart enough' to recognize that this shouldn't happen? Honest question. Or is it up to the User to not use the reformat code option when the ordering matters?
Thanks!
请先登录再写评论。
When you perform the reformat code action with the rearrange option enabled IntelliJ IDEA will reorder the code based on arrangement rules.
Since you haven't specified the field visibility for @Autowired object, package-private is used by default and the IDE will rearrange it. Here are the default arrangement rules for Java code.
I would recommend two options:
Change the arrangement rules in settings (Preferences/Settings | Editor | Code Style | Java | Arrangement).
Do no use the Rearrange Code checkbox when reformating a file.
See the related documentation page for more information https://www.jetbrains.com/help/idea/reformat-and-rearrange-code.html.