Basics of Spring Framework

Spring Container vs Spring Context vs IOC Container vs Application Context
Spring Container or Spring Context or IOC Container : Manages Spring Beans and their life cycles.
To manage Spring Bean Spring makes use of either :
Bean Factory: Basic Spring Container
Application Context: Advanced Spring Container with enterprise specific features.
-> Easy to use in web applications
-> Easy integration with Spring AOP
Most enterprise application uses Application Context
POJO vs Java Bean vs Spring Bean
POJO (Plain Old Java Object)
No Constraints.
Any Java Object is a POJO
Java Beans
Enterprise Java Beans (No longer in use)
Classes that obey 3 Constraints:
Public no-argument constructor
Allow access to their properties using Getters and Setters
Implements Java Serializable
Spring Beans
Spring Bean is any java Object managed by Spring.
Spring uses IOC containers (BeanFactory or ApplicationContext) to manage these objects.
How can I list all beans managed by spring framework?
context.getBeanDefinationNames() //It will return array of string containing bean names;
Arrays.stream(context.getBeanDefinationNames()).forEach(System.out::println);
What if multiple matching beans are available?
Out of multiple matching beans make one of them primary by annotating @Primary above bean definition.
@Bean (name = "address2")
@Primary
public Address address(){
return new Address("Bharuch", "India");
}
@Bean
public Address address3(){
return new Address("Kutch", "India");
}
public class app02HelloWorldSpring {
public static void main(String[] args) {
var context= new AnnotationConfigApplicationContext(helloWorldConfiguration.class);
System.out.println(context.getBean(Address.class) );
}
}
Now above case when Address.class is called and there are multiple address say address2 and address3. The one with @primary annotation will be printed.
Another Option: @Qualifier
Spring is managing objects and performing auto-wiring.
But aren't we writing code to create object for us, then how do we get Spring to create object for us?
@Component is an annotation that allows Spring to detect our custom beans automatically. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them.
Now how will out main class app03BasicGameJava know where to search for Beans. For that, we have @ComponentScan annotation. It will tell our class where to search for Components. In arguments of ComponentScan we pass pakages which we want to be scanned
With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.
Subscribe to my newsletter
Read articles from Mayank Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
