【问题标题】:should a java library be autowired?java库应该自动装配吗?
【发布时间】: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


【解决方案1】:

你应该注入任何你可能想要替换的东西,例如在单元测试期间。

在这种情况下,您可能想在测试时使用不是从 0 开始的AtomicLong 吗?如果是,那么您需要能够注入一个非默认实例。

【讨论】:

  • 如果是这样,那么AtomicLong 可能是在这里使用的错误抽象。
猜你喜欢
  • 2017-05-11
  • 1970-01-01
  • 2011-01-03
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多