- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- Juha Hinkula
- 218字
- 2021-06-24 14:03:26
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.
- 網(wǎng)絡(luò)協(xié)議工程
- Cisco OSPF命令與配置手冊(cè)
- SEO 20日
- 電子政務(wù)效益的經(jīng)濟(jì)分析與評(píng)價(jià)
- 信息通信網(wǎng)絡(luò)建設(shè)安全管理概要2
- 企業(yè)私有云建設(shè)指南
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- 網(wǎng)管第一課:網(wǎng)絡(luò)操作系統(tǒng)與配置管理
- 局域網(wǎng)組成實(shí)踐
- 物聯(lián)網(wǎng)的機(jī)遇與利用
- 區(qū)塊鏈社區(qū)運(yùn)營(yíng)手冊(cè)
- 物聯(lián)網(wǎng)傳感器技術(shù)與應(yīng)用
- 巧學(xué)活用CISCO網(wǎng)絡(luò)典型配置
- 網(wǎng)絡(luò)設(shè)備配置與調(diào)試項(xiàng)目實(shí)訓(xùn)