One of the features for Java Spring is dependecy injection. When you write seperate classes that are instiantiated into another class as a dependecy its good practice to use @Autowired and @Component instead of using new. Should the variable counter be @Autowired and returned by another class? Below is the example class for @Component. Here is some info on 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));
}
}
You should inject anything that you might want to substitute, e.g. during unit testing.
In this case, would you possibly want to use an AtomicLong
that doesn't start at 0, when testing? If yes, then you need to be able to inject a non-default instance.