Give a few Reasons for using Java? Java is a fun language. Let’s look at some of the reasons: Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection). Object Oriented (OO). Better portability than other languages across operating systems. Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI, EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardized APIs (Application Programming Interfaces).
What is spring Spring is an open source,lightweight,loosely Coupled java framework That allows you to build Enterprise applications. By using Spring you can develop various types Like standalone applications,distributed, Webapplications etc…. Spring handles the infrastructure so you can focus on your application. Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE.
What is a Service Locator? Problem: J2EE makes use of the JNDI interface to access different resources like JDBC, JMS, EJB etc. The client looks up for these resources through the JNDI look-up. The JNDI look-up is expensive because the client needs to get a network connection to the server first. So this look-up process is expensive and redundant. J2EE makes use of the JNDI interface to access different resources like JDBC, JMS, EJB etc. The client looks up for these resources through the JNDI look-up. The JNDI look-up is expensive because the client needs to get a network connection to the server first. So this look-up process is expensive and redundant.
With Service Locator Solution: To avoid this expensive and redundant process, service objects can be cached when a client performs the JNDI look-up for the first time and reuse that service object from the cache for the subsequent look-ups. The service locator pattern implements this technique. Refer to diagram below:
Advantages of ServiceLocator J2EE Design Pattern? expensive and redundant JNDI lookups can be avoided by caching and reusing the already looked up service objects.
Why Dependency Injection What’s wrong here? public class Mechanic { public void fixCar() { PhillipsScrewdriver tool = new PhillipsScrewdriver(); tool.use(); }
Why Dependency Injection public class Mechanic { public void fixCar() { Tool tool = new PhillipsScrewdriver(); tool.use(); }
Why Dependency Injection This one is better compared to above two public class Mechanic { public void fixCar() { ToolFactory tf = ToolFactory.getInstance(); Tool tool = tf.getTool(); tool.use(); }
public class Mechanic { public void fixCar() { InitialContext ctx = null; try { ctx = new InitialContext(); Tool quest = (Tool) ctx.lookup( "java:comp/env/Tool"); tool.use(); } catch (NamingException e) { } finally { if(ctx != null) { try {ctx.close(); } catch (Exception e) {} }
Why Dependency Injection ? In Deveoping huge systems using the Object Oriented programming methodology ,we Generally divide the system into Object’s where each of the Object’s represents Some functionality. In this case ,the Objects in the system use some other objects(dependencies) to complete given Request. The Traditional ways of obtaining the dependcies are by creating the dependencies With new operator and constructors (OR) by pulling the dependencies using some Factory methods (OR) from Naming Registry. But these approaches result in some problems which are described below The complexity of the application increases The development increases the difficulty for unit testing increases To Solve the above problems we have to use a push model.that is ,inject the dependent objects into our object instead of creating (OR) pulling the dependent Objects.
What is DI? The Process of Injecting (pushing) the dependencies into an object (dependent) Object is known as Dependency Injection(DI). This gives some benefits the Application development will become faster Dependency will be reduced(that is it will provide the loose coupling ) DI provides a proper test enviroment.
With DI Constructor DI public class Mechanic { private Tool tool; Setter DI public class Mechanic { private Tool tool; public void setTool(Tool tool) { this.tool = tool; } public void fixCar() { tool.use(); Constructor DI public class Mechanic { private Tool tool; public Mechanic(Tool tool) { this.tool = tool; } public void fixCar() { tool.use();
What is IOC? IoC is also known as dependency injection (DI) IOC is a design principle . IOC is describing an external entity (that is container) used to wire the Object’s Creation time by injecting there dependencies. This is fundamentally the inverse,hence the name Inversion of control(IOC),of the bean It-self being in control of instantiating (OR) locating it’s dependencies on it’s own using direct construction of classes,(OR ) something like the ServiceLocator Pattern.
Types of IOC? IOC is broad concept . IOC is two types 1) dependency lookup 2) dependency injection Dependency lookup is a very old technique. In Dependency lookup container provides Callbacks to components and a lookup context. The managed Object’s are responsible for their Other lookups.This is the EJB Approach. Here we need to use JNDI to look up other EJB’s And resources .There are some problems in this implementation. The class needs an Application Server Environment as it is Depedent on JNDI and it is hard to test as we need to provide a dummy JNDI contest for testing purpose.
In the dependency Injection application Object’s are not responsible for looking up resources they depend on. Instead IOC container configures the object Externalizing resources lookup from application code into the container,t hat is Dependencies are injected into object’s Thus lookups are completely removed from Application object’s and it can be used outside the container also. In this approach,the objects can be populated via Setter injection (OR) constructor injection.
Here a few reasons why a JNDI look up is not Elegant : Why dependency injection is more elegant than a JNDI lookup to decouple client and Service? Here a few reasons why a JNDI look up is not Elegant : The client and service being lookedup must Agree on a string based name. The JNDI lookup code is verbose with it’s own Try-catch block,which is repeated acrosss the application. But DI is more elegant because it promotes loose coupling with minimal effort. Dependency is injected into requesting piece of code by the IOC containers Elegant :- graceful and stylish in appearance (OR)solution to a problem
What is Spring Bean Any java class that are controlled by Spring Container are known as Spring Bean
Which injection is better? Setter injection is always preferable ,because we can change the dependency value any no.of times as we required . But with constructor injection we can’t change dependency object value when we require.
What is BeanFactory? The root interface for accessing a Spring bean container And IT is an implementation of the factory Design pattern. BeanFactory is the actual representation of the Spring IOC ontainer The BeanFactory container instantiate and managed the lifecycle of the beans. That is container manages bean objects – from instantiation to destruction When BeanFactory container is acitivated it does not creates any spring bean class Objects. It creates the spring bean class Objects completes the Dependecy Injection only when the getBean(-) is called. There are a number of implementations of the BeanFactory interface .The most commonly used BeanFactory implementation is the XmlBeanFactory class XmlBeanFactory loads beans based on the definations Contained in an XML File. To create an XMLBeanFactory ,we can pass resource object reference to constructor. The resource will creare an InputStream object.
What is Bean Inheritance? Inheritance is the concept of reusing the existing functionality . In case of java you can inherit a class fom an interface (OR) another class.when you inherit a class from another class,your child (OR) Derived class get’s all the functionalities of Your base class. When it comes to spring Bean Inheritance,it talks about how to reuse the existing bean configuration instead of re-defining again.Let’s consider a scenari where your class contains 5 attributes , if we want to configure it as a spring bean you need to inject values for 5 attributes via constructor (OR) setter injection. If we want to create 20 beans of that class ,we need to configure for all the 20 beans for setter (OR)constructor injection. In case If most of the attributes has same value,even then also we need to re-write the configuration.This leads to dulicate configiration declaration in high amount of maintenance. Example code for bean inheritance :- public class Student{ private int studentId; private String studentName,email,gender; private int age; //setters and getters }
BeanInheritance continue… In order to avoid this you can declare the configuration in one bean which acts as parent bean.And All the remaining 19 bean Declarations can inherit their declaration values from the parent bean,so that we don’t need to repeatedly wirte the same configuration in all the child beans.. In this way if we modify the attribute value in parent bean,it will automatically reflects in all It’s 19 child beans. The child bean can override the inherited value of parent by re-declaring at the child level. myBeans.xml ========= <bean id=“baseStudent” class=“com.nareshit.bean.Student” abstract=“true”> <property name=“studentId” value=“1001”/> <property name=“studentName” value=“rama”/> <property name=“age” value=“25”/> <property name=“email” value=“rama@gmail.com”/> <property name=“gender” value=“Male”/> </bean> <bean id=“childStudent” class=“com.nareshit.bean.Student” parent=“baseStudent”> <property name=“age” value=“27”/> <property name=“gender” value=“M”/> In the above cfg we declared baseStudent as abstract which means spring IOC container will not Instantiate the object for the bean declaration.But it acts as a base bean from it’s property values Will be inherited to child beans
What is collection merging? In spring 2.0 the container supports the collection merging. In this your parent bean can declare a list as parent list.In your child beans you can declare a list with values ,you can inherit the values of your parent list values into your child bean list values .As the list merged with parent list values,this is called Collection merging. public class Course{ private List<String> subjects; //setter and getter } <bean id=“parentCourse” class=“Course” abstract=“true”> <property name=“subjects”> <list><value>c</value> <value>c++</value> <value>java</value></list> </property> <bean id=“childCourse” class=“Course” parent=“parentCourse”> <list merge=“true”> <value>java</value></list> </property>
Bean Aliasing In Spring when you configure a class as bean you will declare an id with which you want to retrieve it back from the container. Along with id you ca attach multiple names to beans, and these names act as alias names with which you can look up the bean from the container. To declare multiple names multiple names You need to declare an “name” attribute at the bean tag level . We can separate multiple names with comma
what is parent and child containers in Spring ? Spring supports setting parent-child relationship between two IoC contains If we have two beanFactory containers in the Application, we can set one BeanFactory into Another beanFactory to allow the beans in one bean factory to refer to the beans of other factory.in this we can declare one beanfactory as a parent and other as a child. This is similar to concept of base class and Derived classes.Derived Class can access the properties of base class,but base classs can not access the properties of derived class. In order to refer to parent beans, we can use tag <ref parent=“ “/> Apart from parent attribute it has local which indicates refer to the local bean.Along with it we have Bean attribute as well,which indicates look in local first if not found then search in parent factory and peform Injection.
Using P& C-Name Space If we want to perform setter injection on a spring bean we need to use <property> tag.Instead of writing length<property> tag declaration under the <bean> tag we can replace with short form of representing the same with p-namespace. In order to use the p-namespace,you first need to import the “htttp:www.springframework.org/schema/p” Name space in the spring bean cfg file. Xmlns:p=“htttp:www.springframework.org/schema/p” Xmlns:c=“htttp:www.springframework.org/schema/c”
Perform the injection as p:propertyname=“value” (OR) Once you have imported it,you have to write the attribute at the <bean> tag level to Perform the injection as p:propertyname=“value” (OR) P:propertyname-ref=“refbean” C-Namespace has been introduced in spring 3.1.1, in order to perform constructor injection we need to use<constructor-arg> tag.instead of writing the length <constructor-arg> tag,we can replace it with c:namespace. The syntax for Writing the C-NameSpace is c:argument=“value” (OR) c:argument-ref=“refbean” public class Student{ private int sid; Private String name; //required setters and getters } myBeans.xml <beans> <bean id=“student1” class=“Student” p:sid=“1001” p:name=“sathish”/> <bean id=“student2” class=“Student” p:sid=“1002” p:name=“ramu”/>