官术网_书友最值得收藏!

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. 

主站蜘蛛池模板: 佛冈县| 遂昌县| 石河子市| 文成县| 兴文县| 上高县| 马公市| 大安市| 永寿县| 鲜城| 周宁县| 聊城市| 塔城市| 刚察县| 靖西县| 德钦县| 南皮县| 内黄县| 娄底市| 佛山市| 澎湖县| 邮箱| 永登县| 同德县| 大渡口区| 海城市| 浦城县| 鲁山县| 扎兰屯市| 静海县| 兴城市| 阳曲县| 旬邑县| 忻城县| 错那县| 新津县| 额济纳旗| 桦南县| 河北区| 彝良县| 旬邑县|