Sunday, December 14, 2025

Java notes 5

 1. Create Maven Java project

Click File - New - Others - Type maven - Select Maven Project - Click Next

 

Check "Create Simple Project" checkbox - Click Next

 

Group id: com.pack (any package name)

Artifact id: Spring1 (any project name)

Packaging: jar

 

Click Finish

 

2. Configure spring dependency in pom.xml

 

              <dependencies>

                             <dependency>

                                           <groupId>org.springframework</groupId>

                                           <artifactId>spring-core</artifactId>

                                           <version>5.3.0</version>

                             </dependency>

                             <dependency>

                                           <groupId>org.springframework</groupId>

                                           <artifactId>spring-context</artifactId>

                                           <version>5.3.0</version>

                             </dependency>

              </dependencies>

 

3. C:\Spring\Spring1>mvn clean install

 

4. Right click project - Maven - Update Project - Check "Force Update of Snapshot release" - Click ok

 

5. Create bean program inside src/main/java

 

public class Student {

    private Integer id;

    private String name;

    private Integer age;

              public Integer getId() {

                             return id;

              }

              public void setId(Integer id) {

                             this.id = id;

              }

              public String getName() {

                             return name;

              }

              public void setName(String name) {

                             this.name = name;

              }

              public Integer getAge() {

                             return age;

              }

              public void setAge(Integer age) {

                             this.age = age;

              }

   

    

}

 

public class Employee {

    private Integer id;

    private String name;

    private Double salary;

    private int age;

              public Employee(Integer id, String name, Double salary, int age) {

                             super();

                             this.id = id;

                             this.name = name;

                             this.salary = salary;

                             this.age = age;

              }

              public Employee() {

                             super();

                             // TODO Auto-generated constructor stub

              }

              @Override

              public String toString() {

                             return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + ", age=" + age + "]";

              }

   

    

}

 

 

6. Configure bean prg inside xml file and perform DI

 

Create xml file in any name inside classpath (ie) src folder or inside project folder

   - contains one root element called <beans> and each bean prg is configured by <bean> tag which contains 2 important attributes

   1. id - any name - acts as a object of the bean

   2. class - fully qualified path of bean class

 

<?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="stud" class="com.pack.Student">

       <property name="id" value="100"/>

       <property name="name" value="Ram"/>

       <property name="age" value="20"/>

    </bean>

   

    <!-- <bean id="emp" class="com.pack.Employee">

       <constructor-arg name="id" type="java.lang.Integer" value="200"/>

       <constructor-arg name="name" type="java.lang.String" value="Sam"/>

       <constructor-arg name="salary" type="java.lang.Double" value="20000"/>

       <constructor-arg name="age" type="int" value="25"/>

    </bean> -->

   

    <bean id="emp" class="com.pack.Employee">

       <constructor-arg index="0" type="java.lang.Integer" value="200"/>

       <constructor-arg index="1" type="java.lang.String" value="Sam"/>

       <constructor-arg index="2" type="java.lang.Double" value="20000"/>

       <constructor-arg index="3" type="int" value="25"/>

    </bean>

 

</beans>

 

7. Create main class

 

Resource interface - used to locate the xml file - 2 classes

1. ClassPathResource - If xml file is present in classpath (ie) src folder

2. FileSystemResource - If xml file is present in project folder

 

public class Main {

              public static void main(String[] args) {

                             //Resource res=new ClassPathResource("hello.xml");  //locate xml file

                             /*Resource res=new FileSystemResource("hello.xml");  //locate xml file

                             BeanFactory bf=new XmlBeanFactory(res);  //load all beans present in xml file

                             Student st=(Student)bf.getBean("stud");  //instantiate bean with id="stud" and perform DI

                             System.out.println(st.getName()+" "+st.getAge());*/

                            

                             ApplicationContext ctx=new FileSystemXmlApplicationContext("hello.xml");

                             Employee e=(Employee)ctx.getBean("emp");

                             System.out.println(e);

                            

              }

}

Scope

  - lifetime of bean object - 5 types

1. singleton - default - how many bean object we are creating it will have same reference

2. prototype - how many bean object we are creating it will have different reference

3. request

4. session

5. global-session

 

<bean id="emp" class="com.pack.Employee" scope="prototype">

       <constructor-arg index="0" type="java.lang.Integer" value="200"/>

       <constructor-arg index="1" type="java.lang.String" value="Sam"/>

       <constructor-arg index="2" type="java.lang.Double" value="20000"/>

       <constructor-arg index="3" type="int" value="25"/>

    </bean>

 

ApplicationContext ctx=new FileSystemXmlApplicationContext("hello.xml");

                             Employee e=(Employee)ctx.getBean("emp");

                             System.out.println(e);

                             Employee e1=(Employee)ctx.getBean("emp");

                             System.out.println(e1);

                             Employee e2=(Employee)ctx.getBean("emp");

                             System.out.println(e2);

 

Injecting Collections

    - Apart from primitive datatype we can also inject collection like List(ordered and duplicates allowed), Set(unordered and no duplicates), Map(unique key value pairs), Properties(unique key value pairs but both key and value should be in the form string)

 

public class InjectingCollection {

  private List nameList;

  private Set nameSet;

  private Map nameMap;

  private Properties nameProp;

public List getNameList() {

              return nameList;

}

public void setNameList(List nameList) {

              this.nameList = nameList;

}

public Set getNameSet() {

              return nameSet;

}

public void setNameSet(Set nameSet) {

              this.nameSet = nameSet;

}

public Map getNameMap() {

              return nameMap;

}

public void setNameMap(Map nameMap) {

              this.nameMap = nameMap;

}

public Properties getNameProp() {

              return nameProp;

}

public void setNameProp(Properties nameProp) {

              this.nameProp = nameProp;

}

 

}

 

<bean id="collection" class="com.pack.InjectingCollection">

        <property name="nameList">

            <list>

               <value>Ram</value>

               <value>Sam</value>

               <value>Tam</value>

               <value>Ram</value>

            </list>

        </property>

        <property name="nameSet">

            <set>

               <value>Ram</value>

               <value>Sam</value>

               <value>Tam</value>

               <value>Ram</value>

            </set>

        </property>

        <property name="nameMap">

            <map>

               <entry key="1" value="Ram"/>

               <entry key="2" value="Sam"/>

               <entry key="3" value="Tam"/>

               <entry key="4" value="Ram"/>

            </map>

        </property>

        <property name="nameProp">

            <props>

               <prop key="one">Ram</prop>

               <prop key="two">Sam</prop>

               <prop key="three">Tam</prop>

               <prop key="four">Ram</prop>

            </props>

        </property>

    </bean>

 

public class Main {

              public static void main(String[] args) {

                            

                             ApplicationContext ctx=new FileSystemXmlApplicationContext("hello.xml");

                             InjectingCollection i=(InjectingCollection)ctx.getBean("collection");

                             System.out.println(i.getNameList());

                             System.out.println(i.getNameSet());

                             System.out.println(i.getNameMap());

                             System.out.println(i.getNameProp());

              }

}

 

 

ref attribute

    - used to refer one bean into an another bean

    - using ref="id of the bean"

 

public class Address {

    private String city;

    private String state;

    private String zipcode;

              public String getCity() {

                             return city;

              }

              public void setCity(String city) {

                             this.city = city;

              }

              public String getState() {

                             return state;

              }

              public void setState(String state) {

                             this.state = state;

              }

              public String getZipcode() {

                             return zipcode;

              }

              public void setZipcode(String zipcode) {

                             this.zipcode = zipcode;

              }

   

    

}

 

 

public class Person {

    private Integer pid;

    private String name;

    private Address address;  //referring another bean

              public Integer getPid() {

                             return pid;

              }

              public void setPid(Integer pid) {

                             this.pid = pid;

              }

              public String getName() {

                             return name;

              }

              public void setName(String name) {

                             this.name = name;

              }

              public Address getAddress() {

                             return address;

              }

              public void setAddress(Address address) {

                             this.address = address;

              }

   

    

}

 

<bean id="addr" class="com.pack.Address">

       <property name="city" value="Chennai"/>

       <property name="state" value="Tamilnadu"/>

       <property name="zipcode" value="123456"/>

    </bean>

    <bean id="person" class="com.pack.Person">

       <property name="pid" value="1000"/>

       <property name="name" value="Jim"/>

       <property name="address" ref="addr"/>

    </bean>

 

public class Main {

              public static void main(String[] args) {               

                             ApplicationContext ctx=new FileSystemXmlApplicationContext("hello.xml");

                             Person p=(Person)ctx.getBean("person");

                             System.out.println(p.getName()+" lives in "+p.getAddress().getCity());

              }

}

 

 

Wiring - referring one bean into another bean using ref attribute

 

 

Autowiring

    - used only in case of referring one bean into another bean

    - Instead of using ref attribute we can go for autowiring to inject one bean into another bean

automatically

 

Types

1. autowire=no - default - where we have to do injection using ref attribute

 

public class Match {

   private String location;

   private String distance;

public String getLocation() {

              return location;

}

public void setLocation(String location) {

              this.location = location;

}

public String getDistance() {

              return distance;

}

public void setDistance(String distance) {

              this.distance = distance;

}

  

   

}

 

public class Player {

   private Integer playerId;

   private String name;

   private Match match;  //referred another bean

public Integer getPlayerId() {

              return playerId;

}

public void setPlayerId(Integer playerId) {

              this.playerId = playerId;

}

public String getName() {

              return name;

}

public void setName(String name) {

              this.name = name;

}

public Match getMatch() {

              return match;

}

public void setMatch(Match match) {

              this.match = match;

}

  

   

}

 

 

<bean id="match" class="com.pack.Match">

       <property name="location" value="Chennai"/>

       <property name="distance" value="1000km"/>

    </bean>

    <bean id="player" class="com.pack.Player"  autowire="no">

       <property name="playerId" value="1000"/>

       <property name="name" value="Virat"/>

       <property name="match" ref="match"/>

    </bean>

 

public class Main {

              public static void main(String[] args) {               

                             ApplicationContext ctx=new FileSystemXmlApplicationContext("hello.xml");

                             Player p=(Player)ctx.getBean("player");

                             System.out.println(p.getName()+" plays at "+p.getMatch().getLocation());

              }

}

 

2. autowire="byName"

        - name of the property = id of the bean, then it will do autowire by name

 

<bean id="match" class="com.pack.Match">

       <property name="location" value="Chennai"/>

       <property name="distance" value="1000km"/>

    </bean>

    <bean id="player" class="com.pack.Player" autowire="byName">

       <property name="playerId" value="1000"/>

       <property name="name" value="Virat"/>

       <!-- <property name="match" ref="match"/> -->

    </bean>

 

3. autowire="byType"

       - datatype of the property should be configured in xml file then it will do autowire by type

 

<bean id="match1" class="com.pack.Match">

       <property name="location" value="Chennai"/>

       <property name="distance" value="1000km"/>

    </bean>

    <bean id="player" class="com.pack.Player" autowire="byType">

       <property name="playerId" value="1000"/>

       <property name="name" value="Virat"/>

       <!-- <property name="match" ref="match"/> -->

    </bean>

 

4. autowire="constructor"

        - similar to byType but it will do injectiion through constructor

 

public class Match {

   private String location;

   private String distance;

public Match(String location, String distance) {

              super();

              this.location = location;

              this.distance = distance;

}

public Match() {

              super();

              // TODO Auto-generated constructor stub

}

@Override

public String toString() {

              return "Match [location=" + location + ", distance=" + distance + "]";

}

  

}

 

 

public class Player {

   private Integer playerId;

   private String name;

   private Match match;  //referred another bean

public Player(Integer playerId, String name, Match match) {

              super();

              this.playerId = playerId;

              this.name = name;

              this.match = match;

}

public Player() {

              super();

              // TODO Auto-generated constructor stub

}

@Override

public String toString() {

              return "Player [playerId=" + playerId + ", name=" + name + ", match=" + match + "]";

}

}

 

<bean id="match1" class="com.pack.Match">

       <constructor-arg name="location" value="Mumbai"/>

       <constructor-arg name="distance" value="2000km"/>

    </bean>

    <bean id="player" class="com.pack.Player" autowire="constructor">

       <constructor-arg name="playerId" value="1001"/>

       <constructor-arg name="name" value="Dhoni"/>

       <!-- <property name="match" ref="match"/> -->

    </bean>

 

public class Main {

              public static void main(String[] args) {               

                             ApplicationContext ctx=new FileSystemXmlApplicationContext("hello.xml");

                             Player p=(Player)ctx.getBean("player");

                             System.out.println(p);

              }

}

 

autowire-candidate="false"

     - If same bean is configured multiple times in xml file, which bean class to be injected, it is decided using autowire-candidate

     - So which bean u dont want to inject then we have to define as autowire-candidate="false"

 

<bean id="match1" class="com.pack.Match" autowire-candidate="false">

       <constructor-arg name="location" value="Mumbai"/>

       <constructor-arg name="distance" value="2000km"/>

    </bean>

    <bean id="match2" class="com.pack.Match">

       <constructor-arg name="location" value="Delhi"/>

       <constructor-arg name="distance" value="3000km"/>

    </bean>

    <bean id="player" class="com.pack.Player" autowire="constructor">

       <constructor-arg name="playerId" value="1001"/>

       <constructor-arg name="name" value="Dhoni"/>

       <!-- <property name="match" ref="match"/> -->

    </bean>

 

primary="true"

    - If same bean is configured multiple times in xml file, which bean class to be injected, it is decided using primary

     - So which bean u want to inject then we have to define as primary="true"

 

<bean id="match1" class="com.pack.Match" primary="true">

       <constructor-arg name="location" value="Mumbai"/>

       <constructor-arg name="distance" value="2000km"/>

    </bean>

    <bean id="match2" class="com.pack.Match">

       <constructor-arg name="location" value="Delhi"/>

       <constructor-arg name="distance" value="3000km"/>

    </bean>

    <bean id="player" class="com.pack.Player" autowire="constructor">

       <constructor-arg name="playerId" value="1001"/>

       <constructor-arg name="name" value="Dhoni"/>

       <!-- <property name="match" ref="match"/> -->

    </bean>

 

 

Spring Annotations

     - used instead of configuring beans inside xml file

 

@Configuration - class level annotation, something like xml file, where we will configure all bean classes (ie) contains collection of beans

 

@Bean - used to indicate it is a bean class

 

@Scope - used to define the scope

 

@Primary - If same bean is configured multiple times, which bean class to be injected

 

 

public class Example1 {

    private String message1;

 

              public String getMessage1() {

                             return message1;

              }

 

              public void setMessage1(String message1) {

                             this.message1 = message1;

              }

   

    

}

 

public class Example2 {

    private String message2;

 

              public String getMessage2() {

                             return message2;

              }

 

              public void setMessage2(String message2) {

                             this.message2 = message2;

              }

   

    

}

 

public class Example3 {

   private String message3;

 

public Example3(String message3) {

              super();

              this.message3 = message3;

}

 

public Example3() {

              super();

              // TODO Auto-generated constructor stub

}

 

@Override

public String toString() {

              return "Example3 [message3=" + message3 + "]";

}

  

   

}

 

@Configuration

public class BeanConfiguration {

 

              @Bean

              public Example1 example1() {

                             return new Example1();

              }

             

              @Bean

              @Scope("prototype")

              public Example2 example2() {

                             return new Example2();

              }

             

              @Bean

              public Example3 example3() {

                             return new Example3("Spring");

              }

              @Bean

              @Primary

              public Example3 example31() {

                             return new Example3("Struts");

              }

              @Bean

              public Example3 example32() {

                             return new Example3("Hibernate");

              }

}

 

 

public class Main {

              public static void main(String[] args) {               

                             ApplicationContext ctx=new AnnotationConfigApplicationContext(BeanConfiguration.class);

                             /*Example1 e1=(Example1)ctx.getBean(Example1.class);

                             e1.setMessage1("Helloworld");

                             System.out.println(e1.getMessage1());

                            

                             Example2 e2=(Example2)ctx.getBean(Example2.class);

                             e2.setMessage2("Welcome");

                             System.out.println(e2.getMessage2());*/

                            

                             /*Example1 e1=(Example1)ctx.getBean(Example1.class);

                             System.out.println(e1);

                             Example1 e2=(Example1)ctx.getBean(Example1.class);

                             System.out.println(e2);             

                             Example1 e3=(Example1)ctx.getBean(Example1.class);

                             System.out.println(e3);

                            

                             Example2 e4=(Example2)ctx.getBean(Example2.class);

                             System.out.println(e4);

                             Example2 e5=(Example2)ctx.getBean(Example2.class);

                             System.out.println(e5);

                             Example2 e6=(Example2)ctx.getBean(Example2.class);

                             System.out.println(e6);*/

                            

                             Example3 e=(Example3)ctx.getBean(Example3.class);

                             System.out.println(e);

              }

}


Handson

1. Create User bean class with id, name, address, salary and inject the values using setter injection, constructor injection and print the output

 

2. In this application, you have different implementations of the Engine interface. Your task is to inject the appropriate Engine implementation into a Car class using Spring autowiring.

 

1. Create the Engine Interface with getType()

2. Create PetrolEngine Class that implements Engine intf

3. Create DieselEngine Class that implements Engine intf

4. Create Car class with displayEngineType(), inject the type of engine using @Autowired

5. In main class, create instance of Car class and display the engine type

 

 

No comments:

Post a Comment