- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- Juha Hinkula
- 218字
- 2021-06-24 14:03:27
DI in Spring Boot
Spring Boot scans your application classes and register classes with certain annotations (@Service, @Repository, @Controller) as Spring Beans. These beans can then be injected using an @Autowired annotation:
public class Car {
@Autowired
private Owner owner;
...
}
A fairly common situation is where we need database access for some operations, and, in Spring Boot, we are using repository classes for that. In this situation, we can inject repository class and start to use its methods:
public class Car {
@Autowired
private CarRepository carRepository;
// Fetch all cars from db
carRepositoty.findAll();
...
}
Java (javax.annotation) also provides a @Resource annotation that can be used to inject resources. You can define the name or type of the injected bean when using resource annotation. For example, the following code shows some use cases. Imagine that we have a resource that is defined as this code:
@Configuration
public class ConfigFileResource {
@Bean(name="configFile")
public File configFile() {
File configFile = new File("configFile.xml");
return configFile;
}
}
We can then inject the bean by using a @Resource annotation:
// By bean name
@Resource(name="configFile")
private ConfigFile cFile
OR
// Without name
@Resource
private ConfigFile cFile
We have now gone through the basics of DI. We will put this into practice in the following chapters.