Decorator Pattern
decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically. The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime, independently of other instances of the same class, provided some groundwork is done at design time.
Strategy Pattern
strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them
Example
Implementation of different types of sorting technologies
Factory pattern
Abstract Factory pattern
Java Interview Questions and Answers. Spring interview Questions. Hibernate interview questions. WebServices Interview Questions
Tuesday, March 29, 2011
Design patterns
Decorator Pattern
decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically. The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime, independently of other instances of the same class, provided some groundwork is done at design time.
Strategy Pattern
strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them
Example
Implementation of different types of sorting technologies
Factory pattern
Abstract Factory pattern
Hibernate Interview Questions
Q: How to integrate Spring with Hibernate?
A: A: The most important part is the spring bean configuration. This config file should contains
A: A: The most important part is the spring bean configuration. This config file should contains
1. dataSource
2. sessionfactory
3. DAOImplSample config file
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.
annotation.AnnotationSessionFactoryBean">
OR
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.vaannila.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myUserDAO" class="com.vaannila.dao.UserDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
Sample DAOImpl
public class UserDAOImpl implements UserDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory){
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public void saveUser(User user) {
hibernateTemplate.saveOrUpdate(user);
}
DAOImpl should extend HibernateDaoSupport or we can set the session using the setter method as above
Tuesday, March 22, 2011
WebServices Interview Questions
What is SOAP?
- SOAP stands for Simple Object Access Protocol
- SOAP is a communication protocol
- SOAP is for communication between applications
- SOAP is a format for sending messages
- SOAP communicates via Internet
- SOAP is platform independent
- SOAP is language independent
- SOAP is based on XML
- SOAP is simple and extensible
- SOAP allows you to get around firewalls
- SOAP is a W3C recommendation
Review WSDL
Services are defined
using six major elements:
- types, which provides data type definitions used to describe
the messages exchanged.
- message,
which represents an abstract definition of the data being transmitted. A
message consists of logical parts, each of which is associated with a
definition within some type system.
- portType,
which is a set of abstract operations. Each operation refers to an input
message and output messages.
- binding,
which specifies concrete protocol and data format specifications for the
operations and messages defined by a particular portType.
- port,
which specifies an address for a binding, thus defining a single communication
endpoint.
- service,
which is used to aggregate a set of related ports.
<?xml version="1.0"
encoding="utf-8"?>
<wsdl:definitions
xmlns:s="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
xmlns:tns="https://taxes.test.com/test/webservices/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
targetNamespace="https://taxes.test.com/test/webservices/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<wsdl:types>
<s:schema
elementFormDefault="qualified"
targetNamespace="https://taxes.test.com/test/webservices/">
<s:element
name="IdHdr" type="tns:IdHdr" />
<s:complexType
name="IdHdr">
<s:sequence>
<s:element
minOccurs="0" maxOccurs="1" name="token"
type="s:string" />
<s:element
minOccurs="0" maxOccurs="1" name="address"
type="s:string" />
</s:sequence>
</s:complexType>
<s:element name="GetSQList">
element names
became classes
<s:complexType />
</s:element>
<s:element
name="GetSQListResponse">
<s:complexType>
<s:sequence>
<s:element
minOccurs="0" maxOccurs="1"
name="GetSQListResult" type="s:string" />
<s:element
minOccurs="0" maxOccurs="1" name="processMessage"
type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
<wsdl:message
name="GetSQListSoapIn">
<wsdl:part
name="parameters" element="tns:GetSQList" />
</wsdl:message>
<wsdl:message
name="GetSQListSoapOut">
<wsdl:part
name="parameters" element="tns:GetSQListResponse" />
</wsdl:message>
<wsdl:message
name="GetSQListIdHdr">
<wsdl:part
name="IdHdr" element="tns:IdHdr" />
</wsdl:message>
<wsdl:portType name="OTPWebServiceSoap">
This became the interface
<wsdl:operation
name="GetSQList"> This became method
in the above interface
<wsdl:documentation
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">-- Get List of
Security Questions --</wsdl:documentation>
<wsdl:input
message="tns:GetSQListSoapIn" />
<wsdl:output
message="tns:GetSQListSoapOut" />
</wsdl:operation>
</wsdl:portType>
<wsdl:binding
name="OTPWebServiceSoap" type="tns:OTPWebServiceSoap">
<soap:binding
transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation
name="GetSQList">
<soap:operation
soapAction="https://taxes.test.com/test/webservices/GetSQList"
style="document" />
<wsdl:input>
<soap:body
use="literal" />
<soap:header
message="tns:GetSQListIdHdr" part="IdHdr"
use="literal" />
</wsdl:input>
<wsdl:output>
<soap:body
use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="OTPWebService"> This will be the class with WSDL location and all
<wsdl:port
name="OTPWebServiceSoap"
binding="tns:OTPWebServiceSoap">
<soap:address
location="http://localhost/test/webservices/otpwebservice.asmx"
/>
</wsdl:port> soap:address location Will became the Endpoint
</wsdl:service>
</wsdl:definitions>
- Type
- Message
- Porttype
- Binding
- Service
Type : The data types used by the web service. We have all xsd imports here
Message : The messages used by the web service
<wsdl:message name="HelloWorldRequest">
<wsdl:part name="header" element="am:TransactionHeader"></wsdl:part>
<wsdl:part name="parameters" element="amt:HelloWorldRequest"></wsdl:part>
</wsdl:message>
<wsdl:message name="HelloWorldResponse">
<wsdl:part name="parameters" element="amt:HelloWorldResponse"></wsdl:part>
</wsdl:message>
PortTpe : The operations performed by the web service
<wsdl:portType name="HelloPort">
<wsdl:operation name="HelloWorld">
<wsdl:input message="am:HelloWorldRequest" />
<wsdl:output message="am:HelloWorldResponse" />
</wsdl:operation>
</wsdl:portType>
Binding: The communication protocols used by the web service and message format.
Service : A collection of related end points
Documentation
WSDL uses the optional wsdl:document element
as a container for human readable documentation. The content of the element is
arbitrary text and elements ("mixed" in XSD). The documentation
element is allowed inside any WSDL language element.
SOAPAction
<wsdl:binding name="OTPWebServiceSoap" type="tns:OTPWebServiceSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="GetVersion">
<soap:operation soapAction="https://taxes.test.com/test/webservices/GetVersion" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
<soap:header message="tns:GetVersionIdHdr" part="IdHdr" use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
The SOAPAction URI is used to uniquely identify
the particular operation of a service. As stated in the specification,. it is
must for SOAP over HTTP.
SOAPAction is generally a combination of a web-service namespace and operation name like - http://abc.com/ws/ServiceName/1.0/OperationName wherehttp://abc.com/ws/ServiceName/1.0 is a meaningful namespace which represents that service "ServiceName" is a web-service (ws) of enterprise abc and it's version is 1.0
Above one is an example only and it may vary across the organizations and implementations because of the standards but ultimately it is represented in that context only whereas location attribute of soap:address element is always an address where service is available. In case of SOAP over HTTP, location attribute will hold a HTTP/HTTPS URL where this service is exposed and for any user to consume this service, will have to hit that URL.
SOAPAction is generally a combination of a web-service namespace and operation name like - http://abc.com/ws/ServiceName/1.0/OperationName wherehttp://abc.com/ws/ServiceName/1.0 is a meaningful namespace which represents that service "ServiceName" is a web-service (ws) of enterprise abc and it's version is 1.0
Above one is an example only and it may vary across the organizations and implementations because of the standards but ultimately it is represented in that context only whereas location attribute of soap:address element is always an address where service is available. In case of SOAP over HTTP, location attribute will hold a HTTP/HTTPS URL where this service is exposed and for any user to consume this service, will have to hit that URL.
Q: Difference between RPC and document style in WSDL Binding
The <wsdl:binding> element of the WSDL contains a pair of parameters that influence the form of the resulting SOAP messages: binding style (RPC or document) and use (encoded or literal).
Style. Mostly we will be using document not RPC
Document: the content of <soap:Body> is specified by XML Schema defined in the <wsdl:type> section. It does not need to follow specific SOAP conventions.
RPC: The structure of an RPC style <soap:Body> element needs to obay some specifications
Use
use="literal" means that the type definitions literally follow an XML schema definition.
use="encoded" refers to the representation of application data in XML, usually according to the SOAP encoding rules.
How to resolve NameConflicts while generating stubs?
Error
Thrown by JAXB : A class/interface with the same name "com.." is already in use. Use a class customization to resolve this conflict. at line 945 column 7 of schema http://.../amtpf.asmx?WSDL
Use the below extra arg in pom.xml to solve this
<extraargs>
<extraarg>-autoNameResolution</extraarg>
</extraargs>
Or Use a binding xml like below so that you will have control over the class names
<bindingFiles>
<bindingFile>
${basedir}/resources/sample jaxws_binding.xml
</bindingFile>
</bindingFiles>
Sample sample jaxws_binding.xml
<jaxws:bindings wsdlLocation="w2.wsdl"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb
http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd
http://java.sun.com/xml/ns/jaxws
http://java.sun.com/xml/ns/jaxws/wsdl_customizationschema_2_0.xsd">
<jaxws:bindings
node="wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='http://schemas.test.com/DDM/Tax']">
<jaxb:bindings
node="xs:complexType[@name='GL1099R']/xs:sequence/xs:element[@name='RECID']">
<jaxb:property name="DRTType"/>
</jaxb:bindings>
<jaxb:bindings
node="xs:complexType[@name='FDB_L5_DIVIDEND']/xs:sequence/xs:element[@name='RECID']">
<jaxb:property name="RECID22"/>
</jaxb:bindings>
How to Add soap header?
Add this in pom.xml
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/resources/w2.wsdl</wsdl>
<extendedSoapHeaders>true</extendedSoapHeaders>
</wsdlOption>
</wsdlOptions>
How to give custom wsdl URL path
<wsdlOption>
<wsdl>${basedir}/resources/amtpf.wsdl</wsdl>
</wsdlOption>
And in the Client side Use the below code
URL url = OTPWebService.class.getClassLoader().getResource("createAccount.wsdl");
if (url == null) {
System.out.println("Can not initialize the default wsdl "+OTPWebService.class.getClassLoader().getResource("createAccount.wsdl"));
}
WSDL_LOCATION = url;
How to make WSDL location null
Map<String, Object> requestContext = ((BindingProvider)otpServiceSoap).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://domain/webservices/otpwebservice.asmx");
How to resolve NameConflicts while generating stubs?
Error
Thrown by JAXB : A class/interface with the same name "com.." is already in use. Use a class customization to resolve this conflict. at line 945 column 7 of schema http://.../amtpf.asmx?WSDL
Use the below extra arg in pom.xml to solve this
<extraargs>
<extraarg>-autoNameResolution</extraarg>
</extraargs>
Or Use a binding xml like below so that you will have control over the class names
<bindingFiles>
<bindingFile>
${basedir}/resources/sample jaxws_binding.xml
</bindingFile>
</bindingFiles>
Sample sample jaxws_binding.xml
<jaxws:bindings wsdlLocation="w2.wsdl"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb
http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd
http://java.sun.com/xml/ns/jaxws
http://java.sun.com/xml/ns/jaxws/wsdl_customizationschema_2_0.xsd">
<jaxws:bindings
node="wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='http://schemas.test.com/DDM/Tax']">
<jaxb:bindings
node="xs:complexType[@name='GL1099R']/xs:sequence/xs:element[@name='RECID']">
<jaxb:property name="DRTType"/>
</jaxb:bindings>
<jaxb:bindings
node="xs:complexType[@name='FDB_L5_DIVIDEND']/xs:sequence/xs:element[@name='RECID']">
<jaxb:property name="RECID22"/>
</jaxb:bindings>
How to Add soap header?
Add this in pom.xml
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/resources/w2.wsdl</wsdl>
<extendedSoapHeaders>true</extendedSoapHeaders>
</wsdlOption>
</wsdlOptions>
How to give custom wsdl URL path
<wsdlOption>
<wsdl>${basedir}/resources/amtpf.wsdl</wsdl>
<wsdlLocation>classpath/createAccount.wsdl</wsdlLocation>
</wsdlOption>
And in the Client side Use the below code
URL url = OTPWebService.class.getClassLoader().getResource("createAccount.wsdl");
if (url == null) {
System.out.println("Can not initialize the default wsdl "+OTPWebService.class.getClassLoader().getResource("createAccount.wsdl"));
}
WSDL_LOCATION = url;
How to make WSDL location null
<extraargs>
<extraarg>-client</extraarg>
<extraarg>-wsdlLocation</extraarg>
<wsdlurl />
</extraargs>
How to set dynamic endpoint in WS Client?Map<String, Object> requestContext = ((BindingProvider)otpServiceSoap).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://domain/webservices/otpwebservice.asmx");
Friday, March 18, 2011
Spring Interview Questions
Q: What is IOC (or Dependency Injection)?
A: The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
Q: What are the different types of IOC (dependency injection) ?
A: Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Spring supports only Constructor and Setter Injection
<bean id="Spring3HelloWorldBean"
class="com.test.main.Spring3HelloWorld" >
<!-- Constructor Injection
<constructor-arg type="java.lang.String" value="Ganesh" />
<constructor-arg type="int" value="20" />
-->
<!-- Setter Injection -->
<property name="name" value="Eswar" />
<property name="age" value="24"/>
</bean>
Q: What are the advantages of Spring framework?
A:
Q:What is the difference between Bean Factory and Application Context ?
A: Main difference is "Lazy loading vs. pre-loading beans with Spring Framework"
Spring framework can instantiate and bind (called loading) related Java objects (called beans) according to a given configuration. An XML file can easily be used to define these bindings. Spring framework supports two different types of loading methods; lazy loading and pre-loading respectively managed by BeanFactory and ApplicationContext containers.
Lazy Loading
A bean is loaded only when an instance of that Java class is requested by any other method or a class. org.springframework.beans.factory.BeanFactory (and subclasses) container loads beans lazily. Following code snippet demonstrate lazy loading, concentrate on how "beans.xml" spring configuration file is loaded by BeanFactory container class.
BeanFactory factory = new XmlBeanFactory(
new InputStreamResource(
new FileInputStream("beans.xml"))); // 1
Employee emp = (Employee) factory.getBean("employeeBean"); // 2
Even though "beans.xml" configuration file is loaded with BeanFactory container in line number 1, none of the beans will be instantiated. Instantiation takes place only at line number 2, where bean called "employeeBean" is requested from container. Since the class is instantiated at getBean() method call, time spend to return this method will vary depending on the instantiated object.
Pre-loading
All beans are instantiated as soon as the spring configuration is loaded by a container. org.springframework.context.ApplicationContext container follows pre-loading methodology.
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml"); // 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2
As all singleton beans are instantiated by container at line number 1, this line will take some considerable time to complete. However line number 2 will return the bean instance immediately since instances are already available inside the container.
Decision should be taken based on the requirement of when the instance should be created also think about the memory as ApplicationContext loads all the instances specified in the config file all together.
Q:Autowiring collaborators
Constructor Injection vs. Setter Injection
If the question is which one is better, go with constructor injection
Setter-Injection
The basic-ideas is that you have a no argument-constructor which creates the object with “reasonable-defaults” .
Constructor-Injection
The basic idea with constructor-injection is that the object has no defaults and instead you have a single constructor where all of the collaborators and values need to be supplied before you can instantiate the object. At first it may seem that setter injection is preferred since you have no argument constructors which will make it easy for you to create the object in production and test. However, there is one non-obvious benefit with constructor injection, which in my opinion makes it a winner. Constructor-injection enforces the order of initialization and prevents circular dependencies. With setter-injection it is not clear in which order things need to be instantiated and when the wiring is done. In a typical application there may be hundreds of collaborators with at least as many setter calls to wire them together. It is easy to miss a few setter calls when wiring the application together. On the other hand constructor-injection automatically enforces the order and completeness of the instantiated.
For example lets say we are making DB connection, so the order of flow will be some what like this
ServiceClass->Create DataSource->Init DAOImpl->DAOImpl.getInfoFromDB
In constructor injection we can insure this order by creating a DAOImpl constructor like DAOImpl(ds)
Circular Dependency
If you have a UserService that needs to get information about an employer from CompanyService and the CompanyService needs information about employees from UserService, right there you have a circular dependency.
Spring Bean Scopes Example
OutPut
Without scope="prototype"
Message : Message by custA
Message : Message by custA
With scope="prototype"
Message : Message by custA
Message : null
Bean life cycle
When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. Though, there is lists of the activities that take place behind the scenes between the time of bean Instantiation and its destruction lets discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction.
Initialization callbacks:
To define setup and teardown for a bean, we simply declare the <bean> with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.
Example
package com.test.lifecycle;
import org.springframework.beans.factory.InitializingBean;
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
System.out.println("Inside Init");
}
}
XML based config
Destruction callbacks
public class ExampleBean implements DisposableBean {
public void destroy() {
System.out.println("Inside Destroy");
}
}
XML config
<bean id="exampleBean"
class="examples.ExampleBean" destroy-method="destroy"/>
A: The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
Q: What are the different types of IOC (dependency injection) ?
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Spring supports only Constructor and Setter Injection
<bean id="Spring3HelloWorldBean"
class="com.test.main.Spring3HelloWorld" >
<!-- Constructor Injection
<constructor-arg type="java.lang.String" value="Ganesh" />
<constructor-arg type="int" value="20" />
-->
<!-- Setter Injection -->
<property name="name" value="Eswar" />
<property name="age" value="24"/>
</bean>
Q: What are the advantages of Spring framework?
A:
- Spring has layered architecture. Use what you need and leave you don't need now.
- Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
- Dependency Injection and Inversion of Control Simplifies JDBC
- Open source and no vendor lock-in.
Q:What is the difference between Bean Factory and Application Context ?
A: Main difference is "Lazy loading vs. pre-loading beans with Spring Framework"
Spring framework can instantiate and bind (called loading) related Java objects (called beans) according to a given configuration. An XML file can easily be used to define these bindings. Spring framework supports two different types of loading methods; lazy loading and pre-loading respectively managed by BeanFactory and ApplicationContext containers.
Lazy Loading
A bean is loaded only when an instance of that Java class is requested by any other method or a class. org.springframework.beans.factory.BeanFactory (and subclasses) container loads beans lazily. Following code snippet demonstrate lazy loading, concentrate on how "beans.xml" spring configuration file is loaded by BeanFactory container class.
BeanFactory factory = new XmlBeanFactory(
new InputStreamResource(
new FileInputStream("beans.xml"))); // 1
Employee emp = (Employee) factory.getBean("employeeBean"); // 2
Even though "beans.xml" configuration file is loaded with BeanFactory container in line number 1, none of the beans will be instantiated. Instantiation takes place only at line number 2, where bean called "employeeBean" is requested from container. Since the class is instantiated at getBean() method call, time spend to return this method will vary depending on the instantiated object.
Pre-loading
All beans are instantiated as soon as the spring configuration is loaded by a container. org.springframework.context.ApplicationContext container follows pre-loading methodology.
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml"); // 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2
As all singleton beans are instantiated by container at line number 1, this line will take some considerable time to complete. However line number 2 will return the bean instance immediately since instances are already available inside the container.
Decision should be taken based on the requirement of when the instance should be created also think about the memory as ApplicationContext loads all the instances specified in the config file all together.
Q:Autowiring collaborators
A: The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the
contents of the BeanFactory. The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans will not be autowired. Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, thus saving a significant amount of typing. [2] When using XML-based configuration metadata, the autowire mode for a bean definition is specified by using the autowire attribute of the <bean/> element. The following values are allowed:
- no :No autowiring at all
- byName :Autowiring by property name
- byType :Allows a property to be autowired if there is exactly one bean of the property type in the container. If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set
- constructor :This is analogous to byType, but applies to constructor arguments
- autodetect :Chooses constructor or byType through introspection of the bean class
Q: Given the following class called Car:
public class Cat { public void eat() { System.out.println("Eating"); } }
And given the following Spring config file carconfig.xml:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation=
5 "http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
7
8 <bean id="smallCat" class="Cat" />
Which of the below actions would cause the String "Eating" to be printed out to the console
directly after Spring had initialized the bean called goodCar?
A: Modify line 8 in carconfig.xml to:
<bean id="goodCar" class="Car" init-method="tune" />
Spring AOP
- Aspect - Think of this as the general feature you want to apply globally to your application (logging, performance monitoring, exception handling, transaction management, etc).
- Advice - A chunk of code that is invoked during program execution, and is a piece of the logic for implementing your aspect. This is the first important piece of a Spring AOP aspect implementation! I like to compare advice implementations to the decorator pattern. While an advice doesn't necessarily wrap an entire object in concept, it has the same general effect. We'll learn in a bit that how that advice is applied is more granular/formal than typically defined in the decorator pattern however.
- Joinpoint - A *single* location in the code where an advice should be executed (such as field access, method invocation , constructor invocation, etc.). Spring's built-in AOP only supports method invocation currently, so joinpoints aren't particularly important to focus on at this point.
- Pointcut - A pointcut is a set of many joinpoints where an advice should be executed. So if, in Spring, a joinpoint is always a method invocation, then a pointcut is just a set of methods that, when called, should have advices invoked around them. This is the second important pieces of a Spring AOP aspect implementation!
- Targets/Target Objects - The objects you want to apply an aspect or set of aspects to!
- Introduction - This is the ability to add methods to an object. This is closely tied to, and is almost analogous to the term 'mixins'. It's really just a way to make an object of type A also an object of type B. Introduction in Spring is limited to interfaces.
Constructor Injection vs. Setter Injection
If the question is which one is better, go with constructor injection
Setter-Injection
The basic-ideas is that you have a no argument-constructor which creates the object with “reasonable-defaults” .
Constructor-Injection
The basic idea with constructor-injection is that the object has no defaults and instead you have a single constructor where all of the collaborators and values need to be supplied before you can instantiate the object. At first it may seem that setter injection is preferred since you have no argument constructors which will make it easy for you to create the object in production and test. However, there is one non-obvious benefit with constructor injection, which in my opinion makes it a winner. Constructor-injection enforces the order of initialization and prevents circular dependencies. With setter-injection it is not clear in which order things need to be instantiated and when the wiring is done. In a typical application there may be hundreds of collaborators with at least as many setter calls to wire them together. It is easy to miss a few setter calls when wiring the application together. On the other hand constructor-injection automatically enforces the order and completeness of the instantiated.
For example lets say we are making DB connection, so the order of flow will be some what like this
ServiceClass->Create DataSource->Init DAOImpl->DAOImpl.getInfoFromDB
In constructor injection we can insure this order by creating a DAOImpl constructor like DAOImpl(ds)
Circular Dependency
If you have a UserService that needs to get information about an employer from CompanyService and the CompanyService needs information about employees from UserService, right there you have a circular dependency.
Spring Bean Scopes Example
5 types of bean scopes supported :
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP session.
If no bean scope is specified in bean configuration file, default to singleton.
package com.test.scopes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"bean.xml"});
CustomerService custA = (CustomerService)context.getBean("customerService");
custA.setMessage("Message by custA");
System.out.println("Message : " + custA.getMessage());
//retrieve it again
CustomerService custB = (CustomerService)context.getBean("customerService");
System.out.println("Message : " + custB.getMessage());
}
}
package com.test.scopes;
public class CustomerService {
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
<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-2.5.xsd">
<bean id="customerService"
class="com.test.scopes.CustomerService" scope="prototype"/>
</beans>
Without scope="prototype"
Message : Message by custA
Message : Message by custA
With scope="prototype"
Message : Message by custA
Message : null
Bean life cycle
When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. Though, there is lists of the activities that take place behind the scenes between the time of bean Instantiation and its destruction lets discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction.
Initialization callbacks:
To define setup and teardown for a bean, we simply declare the <bean> with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.
Example
package com.test.lifecycle;
import org.springframework.beans.factory.InitializingBean;
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
System.out.println("Inside Init");
}
}
XML based config
<bean id="exampleBean"
class="com.test.lifecycle.ExampleBean" init-method="init"/>
Destruction callbacks
public class ExampleBean implements DisposableBean {
public void destroy() {
System.out.println("Inside Destroy");
}
}
XML config
<bean id="exampleBean"
class="examples.ExampleBean" destroy-method="destroy"/>
Subscribe to:
Comments (Atom)