如何配置.editorconfig或IntelliJ避免Java中@Inject注解自动换行?
解决Java中@Inject注解与变量同行不被格式化换行的问题
问题描述
我正在配置.editorconfig文件以统一团队编码规范、遵循最佳实践,但遇到一个问题:Java代码中形如@Inject PlaceManager placeManager;的变量注解语句,格式化后会被拆分为两行,希望保留注解与变量同行的格式。
期望保留格式:
@Inject PlaceManager placeManager;
不应被转换为:
@Inject PlaceManager placeManager;
现有.editorconfig配置
# Sample generated with IntelliJ # and https://github.com/hjhgitw/oshi/blob/master/.editorconfig root = true [*] charset = utf-8 end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true # delete whitespace at the end of each line #did try (not exactly knowing what to set) [*.java] ij_java_class_count_to_use_import_on_demand = 1000 # Do not group imports with an asterisk ij_java_names_count_to_use_import_on_demand = 1000 # Do not group imports with an asterisk ij_java_align_multiline_annotation_parameters = false ij_java_annotation_parameter_wrap = off ij_java_class_annotation_wrap = split_into_lines ij_java_do_not_wrap_after_single_annotation = false ij_java_do_not_wrap_after_single_annotation_in_parameter = false ij_java_new_line_after_lparen_in_annotation = false ij_java_rparen_on_new_line_in_annotation = false ij_java_variable_annotation_wrap = off
解决方案
通过.editorconfig配置
在[*.java]区块中添加以下配置项,强制让注解与目标变量保持在同一行:
ij_java_keep_annotation_on_same_line_as_target = true
修改后的[*.java]部分示例:
[*.java] ij_java_class_count_to_use_import_on_demand = 1000 # Do not group imports with an asterisk ij_java_names_count_to_use_import_on_demand = 1000 # Do not group imports with an asterisk ij_java_align_multiline_annotation_parameters = false ij_java_annotation_parameter_wrap = off ij_java_class_annotation_wrap = split_into_lines ij_java_do_not_wrap_after_single_annotation = false ij_java_do_not_wrap_after_single_annotation_in_parameter = false ij_java_new_line_after_lparen_in_annotation = false ij_java_rparen_on_new_line_in_annotation = false ij_java_variable_annotation_wrap = off ij_java_keep_annotation_on_same_line_as_target = true # 保持注解与目标元素同行
通过IntelliJ手动设置(可选)
如果需要在IDE中直接调整,操作路径为:
- 打开
File → Settings(Windows/Linux)或IntelliJ IDEA → Settings(Mac) - 导航到
Editor → Code Style → Java - 切换到
Annotations标签页 - 勾选Keep annotation on the same line as target选项
- 点击
Apply保存设置
内容的提问来源于stack exchange,提问作者Hansjörg Hofer
相关产品推荐
相关产品推荐

