是否应该自动装配Java库?

问题描述 投票:0回答:2

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));
    }
}
java spring dependencies code-injection
2个回答
1
投票

您应该注入您想要替换的任何东西,例如在单元测试中。在这种情况下,您可能想在测试时使用以0开头的AtomicLong吗?如果是,那么您需要能够

注入

一个非默认实例。


-1
投票
使用Spring,您可以轻松地注入对象,这是一个好习惯。依赖项注入有几个优点,例如可以使用模拟对象进行测试,减少类与其依赖项之间的耦合,增加可重用性等等。
© www.soinside.com 2019 - 2024. All rights reserved.