Spring Beans

Using XML as configuration

  1. Add the dependency to pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.16</version>
</dependency>

2. Create a spring.xml in resources folder

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="doctor" class="com.backend.springtok.entity.Doctor">
        <property name="qualification" value="MBBS"/>
        <property name="nurse" ref="nurse"/>
        <constructor-arg value="MBBS"/>
    </bean>

</beans>

3.1 Doctor as example

3. Create a application context

Using Class based configuration

  1. create a config bean class

2. Create class to construct bean of

3. Add this to your spring.xml under the beans tag

4. Create application context to initialise and manage beans

Using the javax.annotation.api , we can annotate different methods at different bean life-cycle to execute some code. Example, in NewDoctor class in above example, we have @PostContruct method which is called after the bean is created by spring.

Creating a protoptye bean inside singleton class

If you declare a prototype bean inside a singleton class, and create 2 different instance of singleton, there prototype bean will also be the same

Last updated

Was this helpful?