首页 > 解决方案 > 注释的顺序在 SB 应用程序中是否重要?

问题描述

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

注释顺序重要吗?

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

这是模块公用

@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 {

}

让有另一个模块 - 高级计算

它具有模块公共作为依赖项(maven 依赖项)。

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

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

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

我想确保如果我们更新commons版本,应用程序不应该中断(API 不应该改变)。CalculationContrioller因此,我在高级计算模块中添加了集成测试。

@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 {

}

标签: javaspringspring-bootintegration-testing

解决方案


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

对我来说 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.

推荐阅读