Thursday, 12 September 2019

Getting Started with Spring Framework

Path for learning spring is

1. Spring framework.
2. Spring MVC
3. Spring Boot


Before beginning to what is Spring Framework we will learn what's the library to get all help from.

http://Spring.io it is a library where u can find all help documents, extensions related to spring.


What is Spring Framework?


Spring is an open source framework and inversion of control for Java Application.

Spring is dependency injection framework.

In an enterprise application many classes depend on many classes where we can take leverage using this framework by injecting this dependency.

How to setup Eclipse for Spring

1. Download Jdk 7 or 8.

2. Download Eclipse.

3. Download CommsApache jar https://commons.apache.org/logging/

4. Download Spring jars https://repo.spring.io/release/org/springframework/spring/5.0.0.RELEASE/
(download dist.zip)

5. Create a new Java Project and add CommsApache.jar and Spring jars.



Create Structure like below

Main class

package com.it.Hellow;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {

 public static void main(String[] args) {
  ApplicationContext apc=new ClassPathXmlApplicationContext("Bean.xml");
  HelloWorld hellow=(HelloWorld)apc.getBean("hellowToWorld");
  hellow.getMessage();

 }
}


Hellow Class

package com.it.Hellow;
public class HelloWorld {
 private String message;
 public String getMessage() {
  System.out.println(message);
  return message;
 }
 public void setMessage(String message) {
  this.message = message;
 }
}


Bean.xml


<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
   <bean id = "hellowToWorld" class = "com.it.Hellow.HelloWorld">
      <property name = "message" value = "Hello World by Anil"/>
   </bean>
</beans>


Output on Running Main class as java application



What is happening here is your are creating a application context and passing it your bean xml name.

Then using that context your are telling what class to refer in that bean.xml using the ID defined in HellowWorld object. When Main class is loaded it pics up bean and supply message property with value Hello World by Anil and therefore prints o/p "hellow Wold by Anil".



What is bean

We can say its an object manage by Spring Framework.


What is Inversion of Control

It means we are giving control from class which needs dependency to Spring Framework.

No comments:

Post a Comment