BACK 
										
									

Spring Tutorial

Spring Tutorial Pre-Requisites: Knowledge on Core Java, MVC Architecture Server-side programming such as Servlets and JSP Database - MySQL Knowledge Spring Tutorial Introduction: · Open-source framework. · To develop robust applications. · Easy and can be developed Fastly. · For enterprise Java applications. · For Creating reusable code · Easily testable · Can be develop high performance applications. · Follows Modular approach. · Supports web MVC Architecture framework. · This is an alternative to struts. · Supports exception handling. · Enables for developing enterprise-class POJO applications. Need not for Extended Java Beans (EJB) container. · Able to work with existing ORM, logging, view technology frameworks. · Supports transaction management. · Support frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. · Spring consists of modules like IOC, AOP, DAO, Context, ORM, WEB MVC etc. · Spring Aspect oriented programming (AOP) allows for distinguishing cross-through (functional) functionality in application. · Functions span multiple application nodes (called cross-cutting concerns). · Cross-cutting nodes are divided from the business logic of the application. · In OOP, class is key unit and in AOP aspect is the key element. · DI used to separate application classes into separate modules. · AOP used to separate cross-cutting concerns from the objects they affect. · AOP implements aspect-oriented programming and allows using the entire arsenal of AOP capabilities. · The Aspects module provides integration with AspectJ, which is also a powerful AOP framework. · Instrumentation is responsible for supporting class instrumentation and class loader, which are used in server applications. · The Messaging module provides STOMP support. · Finally, the Test module provides testing using TestNG or the JUnit Framework. Spring 5 Features · Java 8, Java 9, Java EE 7, Java EE 8, Servlet 4.0, Bean Validation 2.0, and JPA 2.2 is supported. · Improved Logging using Spring-JCL new module. · JUnit 5 supported. · For Kotlin Functional programming. · For NIO 2 streams File operations. · Supports Kotlin, Project Lombok, JSON Binding API as an alternative to Jackson and GSON. · Spring WebFlux and Spring getting Reactive. Spring Framework Web Spring framework Web layer consists of Web, Web-MVC, Web-Socket, Web-Portlet etc. · Web module provides functions like creating web application, downloading files, REST web service etc. · Web-MVC includes web applications Spring MVC implementation. · Web-Socket used in communicating client and the server. · Web-Portlet provides portlet environment MVC implementation. Spring Framework Data Access The Data Access/Integration container consists of JDBC, ORM, OXM, JMS and the Transactions module. · JDBC have JDBC abstract layer, and which reduces the need for registering the loading and connecting the driver. · Spring ORM is for integrating with ORMs like Hibernate, JDO, which follows JPA specification. · OXM module is for linking the Object / XML - XMLBeans, JAXB, etc. · JMS (Java Messaging Service) module is for creating, sending, and receiving messages. · Transaction management for classes which implement specific methods and POJOs. Architecture: Spring AOP Framework · One of the key components of Spring. · AOP used in Spring to provide declarative enterprise services. · Alternative for EJB declarative services. · Example of service is declarative transaction management for building Spring’s transaction abstraction. · User can implement custom aspects, complementing their use of AOP Spring ORM · ORM for database access. · Provides integration layers for: o object-relational mapping APIs o including JDO o Hibernate and iBatis. Spring Web · Is part of Springs web application development stack · Also includes Spring MVC. Spring DAO · Data Access Object supports for standardizing the data access using JDBC, Hibernate or JDO. Spring Context · Package builds on the beans package. · For adding support to message sources and for the Observer design pattern · Which has ability for application objects to obtain resources using a consistent API. Spring Web MVC · Provides the MVC implementations for the web applications. Spring Core · Component provides the Dependency Injection. · BeanFactory provides a factory pattern. · Pattern separates the dependencies such as objects initialization, creation, and access from program logic. Spring Bean · Java whose object which is created and managed by the Spring Container. · A Bean class is one which is except an abstract class and an interface. XML Configuration File · <bean> tag is used in the configuration file. · <bean> is to mark a Java class as a Spring Bean. · Configuration file includes Spring container instructions make the class as a Spring Bean. · Spring Container handles the whole life cycle of that Spring Bean. · Life cycle includes spring bean class loading, creating objects, managing object, and destroying the spring bean class. Example: Student Bean class @Component public class Student{ . . . . } Configuration: <bean id="employee" class="com.dev.example.Student"/> Two types of IoC container interfaces (which acts such as IoC container): 1. BeanFactory (org.springframework.beans.factory.BeanFactory) 2. ApplicationContext (org.springframework.context.ApplicationContext) ApplicationContext interface is built on top of the BeanFactory interface. BeanFactory added with simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application by the ApplicationContext. Creating object for the interface XmlBeanFactory: Resource resource=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(resource); ApplicationContext ClassPathXmlApplicationContext is implements ApplicationContext interface. instantiate ClassPathXmlApplicationContext class to use ApplicationContext: ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Overview DI – Dependency Injection: · Spring supports Dependency Injection (DI) with use of Inversion of Control. · Inversion of Control (IoC) in software engineering, which provides many benefits such as for managing the lifecycle of an object (creation, destruction, invoke…). · IoC is controls the execution flow of program. · IoC helps in decoupling the execution from the implementation, facilitating changes of different implemented code, modularization of the program. · While developing Java application, classes must be independent for testing independently using unit testing. · DI means class A is dependent of class B. and class B will get injected into class A by the IoC. · Dependency injection can be with parameterized constructor or setter methods. · As Dependency Injection is the main concept of Spring Framework. · Lightweight framework. Example: · Design patterns for removing dependency from the programming code. · Dependency between the Employee and Address (tight coupling). class Employee{ Address address; Employee(){ address=new Address(); } } · In the Inversion of Control scenario: · IOC makes the code loosely coupled. · No changes needed when the code moved to new environment. · Testing becomes easy. class Employee{ Address address; Employee(Address address){ this.address=address; } } Example: · Classes Car and Engine. · Car has a object of Engine. Without DI Car class contain object of Engine and instantiated using new operator. Class Car{ Engine engine; getEngine(){ engine=new Engine(); } With Dependency Injection: · Outsourcing instantiation and supply job of instantiating to third party. · Car needs object of Engine to operate. · But it outsources that job to some third party. · The third party, decides instantiation and type to use to create the instance. · Dependency between class Car and class Engine is injected by a third party. · This process needs involvement of some configuration information. · This process is called dependency injection. Benefits of Dependency Injection: · Guarantees configuration and uses of services are separate. · Can change implementations by changing configuration. · Improves Testability as mock dependencies can be injected. · Easy identification of Dependencies. · No need to read code to see what dependencies code works on. Types of Dependency Injection: · Setter Injection o By calling setter methods on beans after invoking a no-argument constructor o or no-argument static factory method to bean instantiation. · Constructor Injection o By calling a constructor with a number of arguments, each representing a collaborator. Interface Injection: In interface-based dependency injection, an interface implementing, it will get the instance injected. Spring Example Steps to create spring application using Eclipse IDE: · Create the java project. · Add spring jar files. · Create the class. · Create the xml file to provide the values. · Create the test class. · Create the class. 1) Create the Java Project · File - New - Project - Java Project. · Provide project name and then click on Finish. · Java project will be created. 2) Add spring jar files - three jar files needed to execute the application. · org.springframework.core-3.0.1.RELEASE-A · com.springsource.org.apache.commons.logging-1.1.1 · org.springframework.beans-3.0.1.RELEASE-A · To execute the application, load only spring core jar files. · To Load jar files in eclipse IDE: Right click on project - Build Path - Add external archives - select all the required jar files - finish.. 3) Create Java class Example: Student class with name property. · xml file used to provide the name of the student. · To create the java class, Right click on src - New - class - Write the class name · Example: Student click on finish. Example: Simple Bean class with getters and setters method package com.example; public class Student { private String name; public String getName() { } public void setName(String name) { } public void displayInfo(){ } } 4) Create the xml file - SpringHelloWorld in src folder - Add content : <?xml version="1.0" encoding="UTF-8"?> <beans <bean id="studentbean" class="com.example.Student"> <property name="name" value="Vishwanath"></property> </bean> </beans> Bean element is used for defining class bean. · The property sub-element of bean specifies the property of the Student class named name. · The value specified in the property element will be set in the Student class object by the IOC container. · Id - is for providing unique identification to bean. · Class - is fully qualified name of class · Property - is used for defining attribute of bean class. 5) Create the test class · Create the java class example Test. · Get the object of Student class from the IOC container using the getBean() method of BeanFactory. package com.example; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource resource=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(resource); Student student=(Student)factory.getBean("studentbean"); student.displayInfo(); } } Run: right click on project->Run as->Java Application Spring XML configuration example 1. Create a simple java maven project. 2. Maven dependency · put spring and cglib maven dependency in pom.xml. <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- cglib required for @configuration annotation --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.0</version> </dependency> </dependencies> <properties> <spring.version>4.2.1.RELEASE</spring.version> </properties> pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"< <modelVersion<4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>SpringHelloWorldJavaBasedConfiguration</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringHelloWorldJavaBasedConfiguration</name> <description>It provides hello world program for java-based config </description> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- cglib required for @configuration annotation --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.0</version> </dependency> </dependencies> <properties> <spring.version>4.2.1.RELEASE</spring.version> </properties> </project> 3. Create Bean class Create a bean class called Country.java in package com.example.model . package com.example.model; public class Country { private String name; private long population; public Country(String name, long population) { super(); this.name = name; this.population = population; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getPopulation() { return population; } public void setPopulation(long population) { this.population = population; } } 4. ApplicationContext.xml Create ApplicationContext.xml in src/main/resources as below. <?xml version="1.0" encoding="UTF-8"?> <?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" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <bean id="country" class="com.example.model.Country"> <constructor-arg index="0" value="India"></constructor-arg> <constructor-arg index="1" value="20000"></constructor-arg> </bean> <context:annotation-config /> </beans> Please note that we are using Constructor injection to inject dependencies here. 5. Create SpringXMLConfigurationMain.java · Create a class named "SpringXMLConfigurationMain.java" in com.example package. package com.example; import com.example.model.Country; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Spring XML based configuration example * */ public class SpringXMLConfigurationMain { public static void main( String[] args ) { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryBean = (Country) ac.getBean("country"); String name = countryBean.getName(); System.out.println("Country name: "+name); long population = countryBean.getPopulation(); System.out.println("Country population: "+population); ac.close(); } } 6. Run it Dependency Injection via Setter method in spring 1.Country.java: · Create simple POJO class with several attributes, · Example: Country and Capital classes. · Create Country.java under package com.example. package com.example; public class Country { String countryName; Capital capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public Capital getCapital() { return capital; } public void setCapital(Capital capital) { this.capital = capital; } } 2.Capital.java · Create simple POJO class with one attribute – "capitalName". · Create Capital.java under package com.example Country class. package com.example; public class Capital { String capitalName; public String getCapitalName() { return capitalName; } public void setCapitalName(String capitalName) { this.capitalName = capitalName; } } 3.ApplicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="CountryBean" class="com.example.Country"> <property name="countryName" value="India"/> <property name="capital" ref="CapitalBean"/> </bean> <bean id="CapitalBean" class="com.example.Capital"> <property name="capitalName" value="Delhi"/> </bean> </beans> We declared two beans with corresponding ids. 1.Class Country with id as "CountryBean" 2.Class Capital with id as "CapitalBean" · Property’s value tag is for assigning value to corresponding attribute. · In xml file, assigned countryName attribute of Country class with value as india. <property name="Name Of Attribute" value="Value Of attribute to be assigned"/> · Property’s ref tag is for assigning reference to corresponding attribute. · In xml file, assigned reference of Capital class to capital attribute of Country class. <property name="Name Of Attribute" ref="id of referencing bean"/> 4.SetterMehtodMain.java · Contains main function. · Create SetterMethodMain.java under package com.example. package com.example; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; public class SetterInjectionMain { public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj = (Country) appContext.getBean("CountryBean"); String countryName=countryObj.getCountryName(); String capitalName=countryObj.getCapital().getCapitalName(); System.out.println(capitalName+" is capital of "+countryName); } } · We have used ClassPathXmlApplicationContext for getting bean. ( can be done in various ways for getting beans). · In hello world example, we used XmlBeanFactory for getting beans. 5.Run it Dependency Injection via Constructor in spring 1.Country.java: · Create a simple class with countryName and capital attributes. · Create Country.java under package com.example following content into Country.java. package com.example; public class Country { String countryName; Capital capital; public Country(String countryName, Capital capital) { super(); this.countryName = countryName; this.capital = capital; } public String getCountryName() { return countryName; } public Capital getCapital() { return capital; } } 2.Capital.java · Create Capital.java under package com.example. · Above Country class contains object of this class. package com.example; public class Capital { String capitalName; public String getCapitalName() { return capitalName; } public void setCapitalName(String capitalName) { this.capitalName = capitalName; } } 3.ApplicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="CountryBean" class=" com.example.Country"> <constructor-arg index="0" type="java.lang.String" value="India" /> <constructor-arg index="1" ref="CaptialBean" /> </bean> <bean id="CaptialBean" class=" com.example.Capital"> <property name="capitalName" value="New Delhi" /> </bean> </beans> Two beans declared with corresponding ids: · 1.Class Country with id as "CountryBean" · 2.Class Capital with id as "CapitalBean" · constructor-arg tag is used for providing argument to bean’ s constructor. · type is for declaring data types and index defines position in constructor’s argument. Two arguments are passed in example. 1. India as string 2. CapitalBean ‘s reference · Property’s value tag is for assigning value to corresponding attribute. so In above xml file,we have assigned capitalName attribute of Capital class with value as Delhi <property name="Name Of Attribute" value="Value Of attribute to be assigned"/> Property’s ref tag is used for assigning reference to the corresponding attribute. so In above xml file, we have assigned reference of Capital class to capital attribute of Country class. <property name="Name Of Attribute" value="id of referencing bean"/> 4.ConstructorDIMain.java This class contains main function.Create ConstructorDIMain.java under package com.example. package com.example; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; public class ConstructorDIMain{ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext ("ApplicationContext.xml"); Country countryObj = (Country) appContext.getBean("CountryBean"); String countryName=countryObj.getCountryName(); String capitalName=countryObj.getCapital().getCapitalName(); System.out.println(capitalName+" is capital of "+countryName); } } · You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans. 5.Run it Spring Bean scopes Bean: · The application objects are managed by the Spring IoC container are called beans. · Bean object that is instantiated, assembled, and otherwise managed by a Spring IoC container. · Beans created with the supplied container configuration metadata in the form of XML <bean/> definitions. · Bean definition contains information called configuration metadata. o How to create a bean o Bean's lifecycle details o Bean's dependencies Bean Properties: Class · attribute specifies the bean class to be used to create the bean (mandatory). Name · attribute specifies the bean uniquely identifier. · In XMLbased configuration metadata, use the id and/or name attributes to specify the bean identifier(s). Scope · This attribute specifies the scope of the objects created from a particular bean definition. constructor-arg · used to inject the dependencies. Properties · used to inject the dependencies. autowiring mode · used to inject the dependencies. lazy-initialization mode · A lazy-initialized bean for IoC container to create a bean instance (on first request – Not startup). initialization method · Called after all required bean properties have been set by the container. destruction method · A callback to be used when the container containing the bean is destroyed. Spring Configuration Metadata · Spring IoC container is totally decoupled from the configuration metadata format. · Three methods to provide Spring Container configuration metadata: o XML based configuration file. o Annotation-based configuration o Java-based configuration · Only one instance is created and the same shared instance is injected in each associated objects. Example: 1.Country.java: · This is simple pojo class country having has name attribute. · Create Country.java under package com.example. package com.example; public class Country { String countryName; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } } 2.ApplicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="country" class=" com.example.Country"> </bean> </beans> 3.ScopesInSpringMain.java · Create main method class under package com.example package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ScopesInSpringMain{ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj1 = (Country) appContext.getBean("country"); countryObj1.setCountryName("India"); System.out.println("Country Name:"+countryObj1.getCountryName()); //getBean called second time Country countryObj2 = (Country) appContext.getBean("country"); System.out.println("Country Name:"+countryObj2.getCountryName()); } } 4.Run it Note: add the code in ApplicationContext.xml for <bean id="country" class="com.example.Country" scope="prototype"> </bean> Initializing collections in spring 1.Country.java: · simple pojo class country having name and list of states attributes. · Create Country.java under package com.example. package com.example; import java.util.List; public class Country { String countryName; List listOfStates; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public List getListOfStates() { return listOfStates; } public void setListOfStates(List listOfStates) { this.listOfStates = listOfStates; } public void printListOfStates() { System.out.println("Some of states in india are:"); for(String state:listOfStates) { System.out.println(state); } } } 2.ApplicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="CountryBean" class=" com.example.Country"> <property name="listOfStates"> <list> <value>Telangana</value> <value>Andhra Pradesh</value> <value>Karnataka</value> </list> </property> </bean> </beans> · initializing collectios(list) country class listofStates attribute. · used list tag. 3.InitializingCollectionsMain.java · Create main method under package com.example. package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InitializingCollectionsMain{ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj = (Country) appContext.getBean("CountryBean"); countryObj.printListOfStates(); } } · Use ClassPathXmlApplicationContext for getting bean. 4.Run it Bean Life Cycle: · Bean is instantiated for get it into a usable state. · Bean is removed from container when no longer required. · Various activities will be taken place between Instantiation and its destruction of a bean. · Declare the <bean> with init method parameters which specifies and called on the bean immediately upon instantiation. · Declare the <bean> for destroy-method parameters specifies and called before a bean is removed from the container. Spring - Bean Scopes · <bean> option of declaring a bean scope. · Declare the bean's scope attribute to be prototype to force Spring to produce a new bean instance each time one is needed. · Declare the bean's scope attribute to be singleton, if Spring to return the same bean instance each time one is needed, you should. Scope and Description: singleton · By default. Scope the bean definition to a single instance per Spring IoC container. prototype · Single bean scopes definition to have any number of object instances. request · HTTP request. Scopes only valid in the context of a Spring ApplicationContext. session · HTTP session. Scopes only valid in the context of a Spring ApplicationContext. global-session · Global HTTP session. Scopes only valid in the context of a Spring ApplicationContext. Example: · Create a project with ExampleSpring under package com.example (in src folder) · Add all necessary Spring libraries using Add External JARs option. · Create Java classes HelloWorld and MainSpring under the com.example package. · Create Beans configuration file Beans.xml under the src folder. · Create the content in Java files. · Create content in Bean Configuration file · Run the application. HelloWorld.java: package com.example; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } MainSpring.java: package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainSpring { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("Hello Java!!!"); objA.setMessage("Object A"); objA.getMessage(); HelloWorld objB = (HelloWorld) context.getBean("Hello Java!!!"); objB.getMessage(); } } Beans.xml with singleton scope: <?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 = "Hello" class = "com.example.HelloWorld" scope = "singleton"> </bean> </beans> Beans Autowiring in spring · Beans automatically wire with auto-wiring feature. · To enable "autowire" attribute in. · The Spring container can auto-wire relationships between collaborating beans. <bean id="countryBean" class="org.example.Country" autowire="byName"> Autowiring modes: no: · Default. no auto wiring. · set it manually via “ref” attribute as we have done in dependency injection via settor method post. byName: · Autowiring by property name. · Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. · It tries to match it with name of bean in xml configuration file. byType: · Autowiring by property datatype. · Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. · It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. · Fatal exception - If more than one such beans exists. contructor: · byType mode in constructor argument. autodetect: · Spring first looks to wire using autowire by constructor, if it does not work, it tries to autowire by byType. Example: 1.Country.java: · Create POJO class having attributes name in Capital class. · Create Country.java under package com.example. package com.example; public class Country { String countryName; Capital capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public Capital getCapital() { return capital; } public void setCapital(Capital capital) { this.capital = capital; } } 2.Capital.java · Create simple POJO class having attribute called "capitalName". · Create Capital.java under package com.example. package com.example; public class Capital { String capitalName; public String getCapitalName() { return capitalName; } public void setCapitalName(String capitalName) { this.capitalName = capitalName; } } 3.BeanAutowirngByNameMain.java · Write main method. · Create BeanAutowiringByNameMain.java under package com.example. package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BeanAutowiringByNameMain{ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj = (Country) appContext.getBean("country"); String countryName=countryObj.getCountryName(); String capitalName=countryObj.getCapital().getCapitalName(); System.out.println(capitalName+" is capital of "+countryName); } } Note: Used ClassPathXmlApplicationContext for getting bean. Note: Used XmlBeanFactory for getting beans. 4.ApplicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="country" class="com.example.Country" autowire="byName"> <property name="countryName" value="India"/> </bean> <bean id="capital" class="com.example.Capital"> <property name="capitalName" value="Delhi" /> </bean> </beans> Note: Used autowire attribute and set it to "byName". Note: Spring container will match "capital" reference in Country class with id or name of other beans in XML configuration file. 5.Run it Limitations with bean autowiring: Overriding possibility · Dependencies can be specified using <constructor-arg> and <property> settings which will always override autowiring. Primitive data types · Primitives, Strings, Classes properties cannot be autowire. Confusing nature · Prefer using explict wiring. (Autowiring is not that extends exact than explicit wiring). Spring and Inheritance: 1.Person.java · Create POJO class with attribute name of Person class. · Create Person.java under package com.example. package com.example; public class Person { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } 2.Employee.java · Create POJO class with attribute called "employeeNumber". · Create Employee.java under package com.example. package com.example; public class Employee extends Person{ int employeeNumber; public int getEmployeeNumber() { return employeeNumber; } public void setEmployeeNumber(int employeeNumber) { this.employeeNumber = employeeNumber; } } 3.ApplicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="personBean" class="com.example.Person"> <property name="name" value="abcd"/> </bean> <bean id="employeeBean" class="com.example.Employee" parent="personBean"> <property name="employeeNumber" value="1234" /> </bean> </beans> 4.InheritanceInSpringMain.java · Create main method. · Create InheritanceInSpring.java under package com.example. package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InheritenceInSpringMain { public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Employee emp=(Employee) appContext.getBean("employeeBean"); System.out.println("Employee name:"+emp.getName()); System.out.println("Employee number:"+emp.getEmployeeNumber()); } } 5.Run it @Autowired Annotation in spring · By default. · Spring containers finds @autowire notation, it autowires bean byType. · Use @Autowire annotation on setter method to get rid of tag in XML configuration file. Example: 1.Country.java: · Create POJO class having attributes name in Capital class. · Create Country.java under package com.example. package com.example; import org.springframework.beans.factory.annotation.Autowired; public class Country { String countryName; Capital capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public Capital getCapital() { return capital; } @Autowired public void setCapital(Capital capital) { this.capital = capital; } } 2.Capital.java · Create pojo class attribute called "capitalName". · Create Capital.java under package com.example. package com.example; public class Capital { String capitalName; public String getCapitalName() { return capitalName; } public void setCapitalName(String capitalName) { this.capitalName = capitalName; } } 3.AutowiredAnnotationInSpringMain.java · Create main method. · Create AutowiredAnnotationInSpringMain.java under package com.example. package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AutowiredAnnotationInSpringMain{ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj = (Country) appContext.getBean("CountryBean"); String countryName=countryObj.getCountryName(); Capital capital=countryObj.getCapital(); String capitalName=capital.getCapitalName(); System.out.println(capitalName+" is capital of "+countryName); } } 4.ApplicationContext.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" 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"> <context:annotation-config/> <bean id="CountryBean" class="com.example.Country"> <property name="countryName" value="India" /> </bean> <bean id="CaptialBean" class=" com.example.Capital"> <property name="capitalName" value="Delhi" /> </bean> </beans> Note: No relationship between above two beans, but @autowired annotation which will automatically wire beans on the basis of type. 5.Run it @Autowired on Constructor: · Use @autowired on constructor also and it will work even if you didn’t define tag in XML configuration file.Make following changes to above code: Country.java: package org.arpit.javapostsforlearning; import org.springframework.beans.factory.annotation.Autowired; public class Country { String countryName; Capital capital; @Autowired public Country(String countryName, Capital capital) { super(); this.countryName = countryName; this.capital = capital; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public Capital getCapital() { return capital; } } ApplicationContext.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" 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"> <context:annotation-config/> <bean id="CountryBean" class="com.example.Country"> <constructor-arg index="0" type="java.lang.String" value="India" /> </bean> <bean id="CaptialBean" class="com.exmaple.Capital"> <property name="capitalName" value="Delhi" /> </bean> </beans> Run it @Autowired with Arugments: · By default. · Dependency is required in the case of @Autowired like @Required. · Use turn off it by passing required=false to @Autowired. Country.java: package com.example; import org.springframework.beans.factory.annotation.Autowired; public class Country { String countryName; @Autowired(required=false) Capital capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public Capital getCapital() { return capital; } } @Required Annotation package com.example; public class Country { Capital capital; @Required public void setCapital(Capital capital) { this.capital = capital; } } · Annotation specifies that the affected bean property must be populated at configuration time (explicit property value in a bean definition or through autowiring). · The container will throw an exception if the affected bean property has not been populated; · NullPointerExceptions raises due to required dependency has not been injected (hard to find problem). · This annotation helps us in debugging the code. Example: 1.Country.java: · Create POJO class having attribute name in Capital class. · Create Country.java under package com.example. package com.example; import org.springframework.beans.factory.annotation.Required; public class Country { String countryName; Capital capital; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public Capital getCapital() { return capital; } @Required public void setCapital(Capital capital) { this.capital = capital; } } 2.Capital.java · Create POJO class having attribute "capitalName". · Create Capital.java under package com.example. package com.example; public class Capital { String capitalName; public String getCapitalName() { return capitalName; } public void setCapitalName(String capitalName) { this.capitalName = capitalName; } } 3.ApplicationContext.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" 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"> <context:annotation-config/> <bean id="CountryBean" class="com.example.Country"> <property name="countryName" value="India" /> </bean> <bean id="CaptialBean" class="com.example.Capital"> <property name="capitalName" value="Delhi" /> </bean> </beans> 4.RequiredAnnotationInSpringMain.java · Create main method in RequiredAnnotationInSpringMain.java under package com.example. package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class RequiredAnnotationInSpringMain{ public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj = (Country) appContext.getBean("CountryBean"); String countryName=countryObj.getCountryName(); Capital capital=countryObj.getCapital(); String capitalName=capital.getCapitalName(); System.out.println(capitalName+" is capital of "+countryName); } } 5.Run it Spring AOP: · Aspect oriented Programming is programming paradigm is similar to object-oriented programming. · Key unit of object-oriented programming is class, similarly key unit for AOP is Aspect. · Aspect enables modularisation of concerns. · AOP works with transaction management across multiple classes and types. · It also refers as a crosscutting-concerns. · Works with business logic for providing pluggable way to apply concern before, after or around. Example – Scenario – logging: · Logging can be put in different classes but for various reasons, if you want to remove logging now, which needed changes in all classes. · But this can be solved by using aspect. · Removing of logging can be done by unplugging that aspect. AOP concepts jargons: · Join point · Advice · Pointcut · Introduction · Target Object · Aspect · Interceptor · AOP Proxy · Weaving Aspect: · Provides modularity · An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name. · AOP breaks-down logic into different parts, is also called concerns. · AOP increases the modularity of a program by cross-cutting concerns. · Need to change all the methods without AOP. · Only one xml file change is enough in case of AOP. Joint Point: · It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution. Advice: · Action taken by aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice. Pointcut: · Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default. Target object: · These are the objects on which advices are applied. For example: There are the object on which you want to apply logging on joint point. AOP proxy: · Spring will create JDK dynamic proxy to create proxy class around target object with advice invocations. Weaving: · The process of creating proxy objects from target object may be termed as weaving. Types of Advices: · Advice is action taken by aspect at particular joint point. 1. Before Advice: executed before a joint point. 2. After Returning Advice: executed after a joint point (without exception). 3. After Throwing Advice: executed if method exits by throwing an exception. 4. After Advice: executed after a joint point irrespective of output. 5. Around Advice: executed before and after a joint point. Spring-ORM · Design Pattern used to access a relational database from an object-oriented language. · ORM (Object Relation Mapping) covers many persistence technologies. They are: JPA(Java Persistence API) · Used for persisting data between Java objects and relational databases. · It is the bridge between object-oriented domain models and relational database systems. JDO(Java Data Objects) · Standard way to access persistent data in databases. · Plain old Java objects (POJO) to represent data persistence. Hibernate · Framework which simplifies Java applications development to interact with the database. Spring Framework and ORM Frameworks · The Spring framework provides HibernateTemplate class (without worrying about create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc). · Because of framework, do not require extra codes before and after the actual database operations (connection, transaction, committing, closing in transaction management). · Spring IoC (Inversion of control) approach with which testing the application becomes easy. · Spring framework offers ORM framework with API for exception. · Using Spring framework, we can set mapping code with explicit template wrapper class or AOP style method interceptor. · hibernate.cfg.xml file consists of all the database information. · applicationContext.xml file consists of all the database information in case of, if we are integrating the hibernate application using spring (don't need to create the hibernate.cfg.xml file). Code without using spring: //creating configuration Configuration cfg=new Configuration(); cfg.configure("hibernate.cfg.xml"); //creating seession factory object SessionFactory factory=cfg.buildSessionFactory(); //creating session object Session session=factory.openSession(); //creating transaction object Transaction t=session.beginTransaction(); Employee e1=new Employee(1234,"abcd",56789); session.persist(e1); t.commit(); session.close(); Using HibernateTemplate class of Spring Framework: Employee e1=new Employee(1234,"abcd",56789); hibernateTemplate.save(e1); Methods of HibernateTemplate class: 1) void persist(Object entity) · Object persistence. 2) Serializable save (Object entity) · Object persistence and returns id. 3) void saveOrUpdate(Object entity) · Object persistence or updates. (save and update) 4) void update(Object entity) · Object updates. 5) void delete(Object entity) · Object deletes on the basis of id. 6) Object get(Class entityClass, Serializable id) · Object Persistence and returns on the basis of given id. 7) Object load(Class entityClass, Serializable id) · Object persistence and returns on the basis of given id. 8) List loadAll(Class entityClass) · Persistence Objects will be returned. Spring Data JPA: · For Providing JpaTemplate class to integrate spring application with JPA. · JPA (Java Persistent API) is the sun specification. · Enterprise application objects will be persisted through Spring JPA. · Alternative for complex entity beans. JPA specification are provided by many vendors like: · Hibernate · Toplink · iBatis · OpenJPA etc. Example: Account.java package com.javatpoint; public class Account { private int accountNumber; private String owner; private double balance; //no-arg and parameterized constructor //getters and setters } Account.xml <entity-mappings version="1.0" xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd "> <entity class="com.example.Account"> <table name="account100"></table> <attributes> <id name="accountNumber"> <column name="accountnumber"/> </id> <basic name="owner"> <column name="owner"/> </basic> <basic name="balance"> <column name="balance"/> </basic> </attributes> </entity> </entity-mappings> AccountDao.java package com.example; import java.util.List; import org.springframework.orm.jpa.JpaTemplate; import org.springframework.transaction.annotation.Transactional; @Transactional public class AccountsDao{ JpaTemplate template; public void setTemplate(JpaTemplate template) { this.template = template; } public void createAccount(int accountNumber,String owner,double balance){ Account account = new Account(accountNumber,owner,balance); template.persist(account); } public void updateBalance(int accountNumber,double newBalance){ Account account = template.find(Account.class, accountNumber); if(account != null){ account.setBalance(newBalance); } template.merge(account); } public void deleteAccount(int accountNumber){ Account account = template.find(Account.class, accountNumber); if(account != null) template.remove(account); } public List<Account> getAllAccounts(){ List<Account> accounts =template.find("select acc from Account acc"); return accounts; } } persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="ForAccountsDB"> <mapping-file>com/example/Account.xml</mapping-file> <class>com.example.Account</class> </persistence-unit> </persistence> applicationContext.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.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mydb" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.Dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.hbm2ddl.autodll">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.deneme</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans> MainClass.java Accountsclient.java package com.javatpoint; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainClass{ public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.class); accountsDao.createAccount(123, "abcd", 12345); accountsDao.createAccount(234, "xyz", 23456); System.out.println("Accounts created"); //accountsDao.updateBalance(123, 24567); //System.out.println("Account balance updated"); /*List<Account> accounts = accountsDao.getAllAccounts(); for (int i = 0; i < accounts.size(); i++) { Account acc = accounts.get(i); System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.getBalance() + ")"); }*/ //accountsDao.deleteAccount(123); //System.out.println("Account deleted"); } } Spring MVC hello world Tools and Technology stack used: · Spring MVC · JDK – 17 · Maven · Apache Tomcat – 10.1 · Eclipse 2023-09 · JSTL - 1.2.1 Creating Maven Web Project 1: Start Eclipse - File->New->Other 2: select Maven->Maven Project, click Next 3: Click Next. And select option with Artifact Id as maven-archetype-webapp. 4: Click Next. Enter Group Id, Artifact Id and version. Group id: is the unique identifier of project. Example: com.example Artifact id: is then name of jar or war (without version). Example: artifact id as SpringMavenWebProject Version: is artifact id version control. If you distribute this project, you may incrementally create different version of it. Click Finish. Refresh your project. 5: Your project structure should like below one. Note: · Project>Properties>Java BuildPath>Libraries, select/change-to appropriate Java version. · Click OK · Maven-update on your project. 6: Update POM.xml based on project requirements / dependencies POM.xml code: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.websystique.maven</groupId> <artifactId>SampleMavenWebProject</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SampleMavenWebProject Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>SampleMavenWebProject</finalName> </build> </project> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.websystique.maven</groupId> <artifactId>SampleMavenWebProject</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SampleMavenWebProject Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <springframework.version>4.0.5.RELEASE</springframework.version> <testng.version>6.8.8</testng.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </pluginManagement> <finalName>SampleMavenWebProject</finalName> </build> </project> Additionally, The Maven plugin maven-compiler-plugin has been added here to explicitly specify the jdk-version we are going to use. Do note that it also forces eclipse to respect the jdk-version being used for the project. if it is not present, and you perform mvn-update from within your eclipse, eclipse switches jdk-version back to default jdk-version [1.5] which is annoying. So do add it in your project pom as well. BACK