- Instead of creating the object by user itself, if we ask spring/ApplicationContext to get the bean/object of it, this process is referred as inversion of control (IOC).
- IOC is kind of container, it will store the all object (i.e beans).
- It is part of Spring.
- ApplicationContext is way to achieve the IOC container.
- How does IOC works ?
- It scans the packages and stores the bean of it.
- How does it know which class/bean to store ?
- It will store all the bean/class which has annotations as -
@Component, @Component - helps the class to automatically register as spring bean.
- It will store all the bean/class which has annotations as -
- Object store at the IOC Container as referred as beans/objects.
- If you want to make a single instance of an object and you wanted to use the same instance globally at your application at different places, then you can make a bean of that class and applicationContext may contain that bean.
- Else if you do not use bean then you to create the instance of that class every time and use it.
- This annotation can only be used once in the entire spring application
- This is also referred as the entry point to the application.
- What does
@SpringBootApplicationdo ? It is made with below 2 annotation@Configuration: This is used at the class level, after using this annotation we can defined@Beaninside the class using methods. And tell spring to make object of these bean as well when the application starts.@EnableAutoConfiguration: This annotations helps spring IOC to autoConfigure/auto register the bean defined in classpath or jar. Ex: for different databases etc.@ComponentScan: Scan and search to beans (searches for @Component, and insert the bean in IOC container/ApplicationContext). Search is done only in the defined package only.
@Autowired/@Inject: These annotations are the annotations which says - to give the object defined in IOC container. This is field injection.import org.springframework.beans.factory.annotation.Autowired; @Autowired private Dog dog;
@RestController: This contains@Componentwhich will help to create bean of this class, also it map the response to json.@RequestMapping: This help us to add additional route to our mapping.
- classPath - list of jar or directories which JVM uses.