Advantages: loosely coupling, lightweight, easy to test, flexible(configurable)
core part of the Spring Framework. It helps in managing lifecycle and configuration of objects.
It performs:
lazy intialization(bean load when getbean called), no annotated injection support
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
MyBean myBean = (MyBean) factory.getBean("myBean");
aggresive intialization, supports annotated injection, superset of BeanFactory
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("C:/path/to/spring-config.xml");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
WebApplicationContext context = new GenericWebApplicationContext(servletContext);
MyBean myBean = context.getBean(MyBean.class);
context.registerShutdownHook(); //a hook ensures that close() method is called when JVM shuts down.
context.stop(); //Temporarily halts application context. restarted by start()
context.close(); //will call preDestroy(), shutdown context, destroy beans
Bean scope:
<bean id="" class="" scope="singleton">.
Annotation Configuration: @Scope("prototype").Bean Lifecycle:
<bean id="" class="" init-method="" destroy-method=""> <beans default-init-method="" default-destroy-method=""/>@PostContruct @PreDestroyBeanFactoryPostProcessor: application context’s internal bean factory after its standard initialization but before any bean instances are created.
BeanPostProcessor:
postProcessBeforeInitialization(Object bean, String beanName): Custom logic before a bean’s initialization callback.
postProcessAfterInitialization(Object bean, String beanName): Custom logic after a bean’s initialization callback.
InitializingBean: afterPropertiesSet(): Method for custom initialization logic after properties are set.
DisposableBean:
destroy(): Method for custom cleanup logic before a bean is destroyed.
Custom Init and Destroy Methods:
initMethod and destroyMethod attributes in @Bean annotation or XML configuration to specify custom initialization and destruction methods.
@PostConstruct: Annotation for a method to be executed after the bean’s properties have been set and before it is put into service.
@PreDestroy: Annotation for a method to be executed before the bean is destroyed.
in applicationContext.xml. high performance, readability is tuff, complex to write.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="car" class="com.example.Car">
<property name="engine" ref="engine"/> <!-- setter injection. ref means another bean id -->
<constrctor-args ref="engine"> <!-- constructor injection ref means another bean id-->
</bean>
<bean id="engine" class="com.example.Engine"/>
</beans>
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Car car = context.getBean(Car.class);
car.start();
}
}
//AppConfig.java
@Configuration
public class AppConfig {
@Bean
public Car car() {
return new Car(engine());
}
@Bean
public Engine engine() {
return new Engine();
}
}
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Car car = context.getBean(Car.class);
@Configuration
@ComponentScan(basePackages = "com.example.ioc.demo")
public class AnnotationJavaConfig {
}
ApplicationContext context = new AnnotationConfigApplicationContext(AnnotationJavaConfig.class);
CarInterface car = context.getBean(Car.class);
@Component //@services //@Respository
class Car{}
| Annotation | Usage | Level |
|---|---|---|
| @Configuration | Indicates a class declares one or more @Bean methods. | Class |
| @Bean | Indicate that method produces a bean. | Method |
| @PostConstruct | method executed after bean initialization. | Method |
| @PreDestroy | method executed before bean destruction. | Method |
| @ComponentScan(“com”) | Specifies the packages to be scanned for annotated classes. | Class |
| @Component | Indicates that a class is a spring bean | Class |
| @Service | Indicate service classes, Identical to @Component | Class |
| @Repository | Inticate DAOimpl/persistence classes, Identical to @Component | Class |
| @Autowired | Enables bean injection for @Component,@Service,@Repository | Field/Method/Constructor |
| @Autowired(required=false) | Spring’ll not fail if bean not found, instead assign null. | Field/Method/Constructor |
| @PropertySource | Specifies a property file @PropertySource(“classpath:app.properties”) | Class |
| @Value | inject values from @PropertySource file @Value(“${my.custom.property}”) | Field |
| @Required | Ensures bean property must be populated otherwise thrownException | Field/Method/Constructor |
| @Qualifier | give bean id, avoid ambiquity when multi implementation exist | Field/Parameter |
| @Lazy | Delays bean creation and intialized when it is first requested. | Class/Method |
| @ConfigurationProperties | Specifies configuration properties for entire POJO classes. | Class |
Note: @Repository Automatically translates database exceptions (e.g., SQLException) into Spring’s consistent DataAccessException hierarchy.
Classes of ApplicationContext:
Types of Spring configurations:
1.XML, 2.Java, 3.Annotation
Steps to create spring bean(IOC via XML):
<bean id="beanId" class="com.ClassName"></bean>ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");InterfaceName obj = (InterfaceName)context.getBean("beanId");Dependency injection via XML:
<property name="color" value="red"/><constructor-arg name="soda" value="True"/><property name="color" ref="anotherBeanName"/><constructor-arg name="color" ref="anotherBeanName"/><context:property-placeholder location="classpath:rasna-info.properties"/> <property name="color" value="${foo.color}"/>Autowire attribute via XML:
## Java approach
Steps to create spring bean(IOC via JAVA):
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);InterfaceName obj = (InterfaceName)context.getBean("beanId");@Bean annotation will be use, beanName will be function name. refer practise repo.
@PropertySource(“classpath:rasna-info.properties”)
-no need of bean defination in xml/java config file, we just mention folder to scan
@ComponentScan(basePackages="com.java.drinkMaker") <context:component-scan base-package="com.luv2code.springdemo"/>ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);InterfaceName obj = (InterfaceName)context.getBean("beanId");Annotation Enabling
<context:annotation-config /><bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">@Component - define class as bean
@Qualifier - give bean id, avoid ambiquity while using autowired
@Autowired - provides dependency
@Value() - field injection directly or via property file
@PropertySource(“classpath:rasna-info.properties”)