Best common pattern: constructor injection
The required helper is listed in the constructor. Spring sees it and provides the right bean.
@Service
class WeatherService {
String forecast() {
return "Sunny with a chance of learning!";
}
}
@RestController
class WeatherController {
private final WeatherService weatherService;
WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@GetMapping("/weather")
String getWeather() {
return weatherService.forecast();
}
}
Field injection: easy, but not the best teaching pattern
Field injection hides what the class needs. Constructor injection makes the needs obvious.
@RestController
class WeatherController {
@Autowired
private WeatherService weatherService;
}
Teacher note: show it exists, but recommend constructor injection for clean, testable code.
Separating configuration from use
The code uses a setting, but the actual value lives outside the class. That means you can change behavior without rewriting the class.
// application.yml
school:
name: Blue Ridge Middle School
// Java class using the setting
@Component
class SchoolBanner {
private final String schoolName;
SchoolBanner(@Value("${school.name}") String schoolName) {
this.schoolName = schoolName;
}
String message() {
return "Welcome to " + schoolName;
}
}