【问题标题】:Does order of annotations matter in SB application?注释的顺序在 SB 应用程序中是否重要?
【发布时间】:2020-05-15 17:32:27
【问题描述】:

在我看来,不同顺序的注释会破坏我的构建。

Does annotations order matter?

上面的答案说,一般来说,注释顺序应该无关紧要。就我而言,它正在崩溃。

这是模块公用

@ConditionalOnProperty(value = "calculatorEnabled", havingValue = "true")
@Component
class Calculator {

// some logic
}
@ConditionalOnBean(Calculator.class)
@Service
class CalculationService {

    private final Calculator calculator;

    @Autowired
    public CalculationService(final Calculator calculator) {
        this.calculator = calculator;
    }
 // some logic
}
@RequestMapping(value = "/calculations", produces = MediaType.APPLICATION_JSON_VALUE)
@ConditionalOnBean(CalculationService.class)
@RestController
class CalculationController {

}

让另一个模块 - 高级计算

具有模块 commons 作为依赖项(maven 依赖项)。

请注意,有两个 Maven 模块是故意的。 所以 CalculationController 在其他使用 commons 依赖的模块中可用。

现在,让我在 高级计算 中进行两个测试。 (再次,我决定在另一个模块中测试CalculationController)。

我知道最好在实际定义组件的模块中进行测试,但是commons模块是很久以前由其他团队编写的;现在我们必须使用它。

我想确保如果我们更新 commons 的版本,应用程序不会中断(API 不会更改)。因此,我将 CalculationContrioller 的集成测试添加到 advanced-calculation 模块中。

@SpringBootTest(classes = [AdvancedCalculationApplication.class],properties = ["calculatorEnabled=true" ])
@AutoConfigureMockMvc
AdvancedCalculationsITTest extends Specification {

}

@SpringBootTest(classes = [AdvancedCalculationApplication.class],properties = ["calculatorEnabled=" ])
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@AutoConfigureMockMvc
AdvancedCalculationsITTestsDisabled extends Specification {

}

mvn clean install 失败,因为 AdvancedCalculationsITTest 失败。错误无法自动连接 CalculationController,因为没有候选 calculationService

但是,当我稍微改变注释的顺序时,它会起作用

@ConditionalOnBean(CalculationService.class)
@RequestMapping(value = "/calculations", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
class CalculationController {

}

【问题讨论】:

    标签: java spring spring-boot integration-testing


    【解决方案1】:

    我会更新这个答案,但稍后会更新。

    对我来说 TODO。 (我会做一个demo,加个github的链接,放一些代码示例)。

    欢迎您的意见和建议!

    我在一个方法上有 2 个自定义注释 (RUNTIME):一个注释使方法始终抛出异常 @Exceptional,另一个 @Catchable 始终捕获异常。为简单起见,让此方法返回 void。通过以不同的顺序放置这些注释,您应该会得到不同的结果。

    @Catchable
    @Exceptional
    public void processAction() {
        // There is nothing that throws an exception.
        safeStatement1();
        safeStatement2();
    
        safeStatementN();
    }
    

    @Exceptional
    @Catchable
    public void processAction() {
        // There is nothing that throws an exception.
        safeStatement1();
        safeStatement2();
    
        safeStatementN();
    }
    
    By having these annotations in different order, the result should be different.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多