Original URL: Spring Registration Bean Series--Method 1: @Component_IT Knives Out Blog-CSDN Blog
Introduction
This article introduces Spring's method of registering beans: @Component.
I have written a series of methods for registering Beans, see: Spring Bean Registration (Providing Beans) Series--Comprehensive Methods_IT Knives Out Blog-CSDN Blog
Method overview
Just add @Component to the bean class. (@Controller/@Service/@Repository is also possible because it contains @Component)
By default, Spring will scan the classes of the package and its sub-packages where the @SpringBootApplication annotation is located, and include these classes into the spring container, as long as the class has the @Component annotation.
The location of this scan can be specified, for example:
@SpringBootApplication(scanBasePackages="com.test.chapter4")
Example
Class (Bean) to be registered
package com.knife.entity;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public String sayHello() {
return "Hello World";
}
}
test
package com.knife.controller;
import com.knife.entity.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private MyBean myBean;
@GetMapping("/test")
public String test() {
return myBean.sayHello();
}
}
result