Java Spring的功能之一是依赖注入。当您编写依赖于另一个类的独立类时,最好使用@Autowired和@Component而不是new。变量计数器应该@Autowired并由另一个类返回吗?下面是@Component的示例类。以下是有关dep inj的一些信息:https://www.tutorialspoint.com/spring/spring_dependency_injection.htm
@Component
class CounterClass {
private final AtomicLong counter;
public CounterClass() {
this.counter = new AtomicLong();
}
}
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
//should counter be @Autowired??
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
您应该注入您想要替换的任何东西,例如在单元测试中。在这种情况下,您可能想在测试时使用以0开头的 注入AtomicLong
吗?如果是,那么您需要能够