【发布时间】:2020-09-04 22:09:05
【问题描述】:
Java Spring 的一个特性是依赖注入。当您编写单独的类并将其实例化为另一个类作为依赖项时,使用@Autowired 和@Component 而不是使用new 的好习惯。变量 counter 是否应该被 @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));
}
}
【问题讨论】:
-
您能更详细地解释一下计数器的用例吗?在服务中保持这样的可变状态并不常见(出于多种原因,包括您通常在不同的服务器上运行应用程序的多个副本),因此计数器的具体使用很重要。如果您需要指标,可以使用专门的系统(千分尺)。
标签: java spring dependencies code-injection