springs

"Spring "


Spring

1 )   What is dependency injection or Inverse of Control ?

Ans)
Inversion of Control (IoC) is an object-oriented
programming practice where the object coupling is bound at run time by an assembler
object and is typically not known at compile time using static analysis.
These Objects can be obtained by means of Dependency lookup or Dependency injection.
Dependency lookup is a pattern where a caller asks the container object for an
object with a specific name or of a specific type.
 Dependency injection is a
pattern where the container passes objects by name to other objects,
via either constructors, properties, or factory methods.



2 )   How many ways you could achieve Dependency Injection in Spring ?

Ans)
Dependency Injection could be accomplished in two ways either with constructor arguments
or with Setter Getter methods.
Setter-based dependency injection is realized by calling setters on your beans after invoking
a no-argument constructor or no-argument static factory method to instantiate your bean. Beans
defined in the BeanFactory that use setter-based dependency injection are true JavaBeans.
<bean id="exampleBean" class="examples.ExampleBean">
  <property name="beanOne"><ref bean="anotherExampleBean"/></property>
</bean>
Constructor-based dependency injection is realized by invoking a constructor with a number of
arguments, each representing a collaborator or property.
<bean id="exampleBean" class="examples.ExampleBean">
  <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
</bean>



3 )   What are the Different Modules of Spring ?

Ans)

  • null
    Sample Img 3
 Inversion of Control container (dependency injection)
o  Aspect-oriented programming framework
o  Data access framework
o  Transaction management framework
o  Model-view-controller framework
o  Remote access framework
o   Batch framework
o  Integration framework




4 )   What is Spring BeanFactory ?

Ans)
The BeanFactory is the actual container which instantiates, configures, and manages a number
of beans
. These beans typically collaborate with one another, and thus have dependencies
between themselves.
You can get the Bean Factory as follows .
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml"});

BeanFactory factory = (BeanFactory) appContext;



5 )   Spring Bean life cycle ?

Ans)

  • Spring Bean life cycle
    Sample Img 5
Spring's bean has a very elaborated life cycle which gives opportunities to hook up some custom code or logic in various life cycle stages. There are two distinct spring containers one is bean factory and another is application context.  More precisely, only one additional phase is added in case of application context.
1. Instantiate: in this phase container finds the bean's definition and instantiates it.
2. Populate properties: in this phase using the dependency injection all the properties are populated which are specified in the bean definiton (in the xml file).
3. Set Bean Name : If BeanNameAware interface is implemented the factory calls the setBeanName() passing the Bean's Id.
4. Set Bean factory: if BeanFactoryAware interface is implemented setBeanFactory() method is called.
5. ApplicationContextAware: This step is valid only if the Application context container is used. In this phase if bean implements the ApplicationcontextAware then setApplicationContext() method is called.
6. Pre-initialization: If any BeanPostProcessors are associated with the bean then their postProcessBeforeInitialization() methods will be called.
7. InitializingBean: If an init-methodis specified for the bean then it is called.
8. Post Initialization: If there are any BeanPostProcessors are associated then postProcessAfterInitialization() is called.
9. Destroy: If bean implements the DisposableBean interface then destroy() method is called.



6 )   How you create Singleton beans by using Spring ?

Ans)
In Spring Beans are defined two modes: singleton or non-singleton.
When a bean is a singleton, only one shared instance of the bean will be managed and all
requests for beans with an id matching that bean definition will result in that one
pecific bean instance being returned.
Beans are deployed in singleton mode by default, unless you specify otherwise.
Please see below you could manage this feature with  'singleton' attribute, please see below.
<bean name="yetAnotherExample"
      class="examples.ExampleBeanTwo" singleton="true"/>



7 )   How to create Prototype beans by using Spring ?

Ans)
The non-singleton, prototype mode of a bean deployment results in the creation of
a new bean instance every time a request for that specific bean is done.
<bean id="exampleBean"
      class="examples.ExampleBean" singleton="false"/>



8 )   What is AutoWire in Spring ? What are the other possible values ?

Ans)
A BeanFactory is able to autowire relationships between collaborating beans. This means
it's 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.
No                  -  No autowiring at all. Bean references must be
                       defined via a ref element. This is the default.

byName              -  Autowiring by property name.
byType              -  Allows a property to be autowired if there
                       is exactly one bean of the property type in the BeanFactory.
Constructor        -  This is analogous to byType, but applies to constructor arguments.
Autodetect         -  Chooses constructor or byType through introspection of the bean class.



9 )   How to get the Spring Context ?

Ans)

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml"});
BeanFactory factory = (BeanFactory) appContext;



10 )   PropertyPlaceholderConfigurer ?

Ans)
The PropertyPlaceholderConfigurer, implemented as a bean factory post-processor, is used
to externalize some property values from a BeanFactory definition, into another separate
file in Java Properties format.
Create PropertyPlaceholderConfigurer  Programmatically :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);
By Config :
 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:your.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>
By Using Util :
<util:properties id="messages" location="classpath:messages.properties"/>
By Using PropertySource :
@Configuration
@PropertySource(name = "someName", value = {"classpath:a.properties", "classpath:b.properties"})
public class MyConfiguration {
}



11 )   How to read Message Sources using Spring Application Context ?

Ans)
Here are the Steps to follow to use Internationalization by reading Message Resource.
1) Add this to your spring config XML .

      <bean id="messageSource" class="org.springframework.context.support.
                  ResourceBundleMessageSource
">
            <property name="basename" value="messages"/>
        </bean>

    2) create a property file name calles "messages.properties" and place that in
    WEB-INF/Classes folder.


    3) Include the following JSTL in jsp.
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  



12 )   Where could you add your Spring Configuration for a Web App ?

Ans)
 Add the following two entries to the Web.xml
Step 1:
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
Step 2:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/spring-ws-servlet.xml</param-value>
</context-param>



13 )   Can you have mulitiple implementations for same bean ?

Ans)
 Yes, you can have this, you need to configure the Parent and Chield Beans as follows.
<bean id="inheritedTestBean" abstract="true"
    class="org.springframework.beans.TestBean">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>
<bean id="inheritsWithDifferentClass"
      class="org.springframework.beans.DerivedTestBean"
      parent="inheritedTestBean" init-method="initialize">

  <property name="name" value="override"/>
  <!-- the age property value of 1 will be inherited from  parent -->
</bean>




14 )    ApplicationContextAware ?

Ans)
A bean which implements this interface and is deployed into the context will be called back
on creation of the bean, using the interface's setApplicationContext() method, and provided
with a reference to the context, which may be stored for later interaction with the context.
public class DefaultBeanLoader implements  ApplicationContextAware {
        private ApplicationContext applicationContext;
                public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                this.applicationContext = applicationContext;
        }
    }



15 )   What is BeanWrapper ? How to use it ?

Ans)
The BeanWrapper offers functionality to set and get property values (individually
or in bulk), get property descriptors, and to query properties to determine if they
are readable or writable.
Company c = new Company();
BeanWrapper bwComp = BeanWrapperImpl(c);

bwComp.setPropertyValue("name", "your Company");



16 )   What is JdbcTemplate ? How to use this ?

Ans)
This is the very important class in the JDBC core package, it simplifies the use of JDBC
since it handles the creation and release of resources. This helps to avoid common errors
like forgetting to always close the connection.
// create a JdbcTemplate and set data source
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);

// create a custom translator and set the datasource for the default translation lookup
MySQLErrorCodesTransalator tr = new MySQLErrorCodesTransalator();
tr.setDataSource(dataSource);
jt.setExceptionTranslator(tr);
// use the JdbcTemplate for this SqlUpdate
SqlUpdate su = new SqlUpdate();
su.setJdbcTemplate(jt);

su.setSql("update orders set shipping_charge = shipping_charge * 1.05");
su.compile();
su.update();



17 )   How to set up "Hibernate SessionFactory setup in a Spring application context" ?

Ans)
<bean id="mySessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
      <list>
        <value>product.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
      </props>
    </property>
  </bean>



18 )   How many ways you can have Hibernate-Spring integration (Inversion of control for Hibernate) ?

Ans)
Could be done in Two ways.
i)By using "HibernateTemplate"
ii) By using  "HibernateDaoSupport" .

With HibernateTemplate and Callback method:
public class YourDaoImpl implements YourDao {
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
   public Collection loadProductsByCategory(final String category) throws DataAccessException {
        HibernateTemplate ht = new HibernateTemplate(this.sessionFactory);
        return (Collection) ht.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(
                    "from test.Product product where product.category=?");
                query.setString(0, category);
                return query.list();
            }
        });
    }
}
By uisng HibernateDaoSupport :
public class YourDaoImpl extends HibernateDaoSupport implements YourDao {
   public Collection loadProductsByCategory(String category)
            throws DataAccessException, MyException {
        Session session = getSession(getSessionFactory(), false);
        try {
            List result = session.find(
                "from test.Product product where product.category=?",
                category, Hibernate.STRING);
            if (result == null) {
                throw new MyException("invalid search result");
            }
            return result;
        }  catch (HibernateException ex) {
            throw convertHibernateAccessException(ex);
        }
    }
}
Similarly you also have the following
i)  "JdoTemplate and JdoDaoSupport"
ii) TopLinkTemplate and TopLinkDaoSupport
iii) n iBATIS API  SqlMapClientTemplate and SqlMapClientDaoSupport




19 )   Spring MVC ?

Ans)
Spring MVC frame work is another popular MVC framework for Web Apps like Struts.
Below is the sample Spring MVC configuration for the Log In Functionality.
Step 1 :
public class StartController extends SimpleFormController  {
 @Override
 protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse
 httpServletResponse, Object o, BindException e) throws Exception {
    StartForm form = (StartForm) o;
    if (form.getCommand().equals("startForm")) {
        return new ModelAndView(new RedirectView("newOrder/newOrder.htm"));
    }
}
  @Override
  protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {
    AddDocumentForm form = new AddDocumentForm();
    return form;
  }
  @Override
  protected Map referenceData(HttpServletRequest request, Object o, Errors errors) throws Exception {
    Map<String, Object> map = super.referenceData(request, o, errors);
    return map;
  }
}
View :
   <bean name="/start.htm" class="com.salesorder.StartController">
        <property name="sessionForm" value="true"/>
        <property name="commandName" value="startForm"/>
        <property name="commandClass" value="com.salesorder.StartForm"/>
        <property name="formView" value="salesorder/start"/>
        <property name="successView" value="start.htm"/>
    </bean>
Resolver :
Views in Spring are addressed by a view name and are resolved by a view resolver,
Spring Offers Several View Resolvers such as "AbstractCachingViewResolver",
"XmlViewResolver","ResourceBundleViewResolver","InternalResourceViewResolver",
"VelocityViewResolver".
Each of the above solves different technical solution and offers different
 functionality.
"InternalResourceViewResolver" is most commonly used one , could be used as follows.
<bean id="viewResolver" class="
org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>
 </bean>



20 )   Spring Integration with JSP-JSTL.

Ans)
Just as with any other view technology you're integrating with Spring, for JSPs you'll
need a view resolver that will resolve your views. The most commonly used view resolvers
when developing with JSPs are the InternalResourceViewResolver and the
ResourceBundleViewResolver. Both are declared in the WebApplicationContext
<bean id="viewResolver" class="org.springframework.web.servlet.view.
          InternalResourceViewResolver
">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>
</bean>
Similarly there are some other resolovers .
i) org.springframework.web.servlet.view.velocity.VelocityViewResolver.
Ii) org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer



21 )   Can you use Structs along with Spring ? Spring - Struts Intergration ?

Ans)
Yes.
 i) ContextLoaderPlugin
To configure this plug-in, add the following XML to the plug-ins section near the bottom of your struts-config.xml file:
The location of the context configuration files can be customized using the "contextConfigLocation" property.
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
  <set-property property="contextConfigLocation"
      value="/WEB-INF/action-servlet.xml.xml,/WEB-INF/applicationContext.xml"/>
</plug-in>
ii) <controller>
  <set-property property="processorClass"
      value="org.springframework.web.struts.DelegatingRequestProcessor"/>
</controller>
iii) ActionSupport Classes
public class YourAction extends DispatchActionSupport {
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
            throws Exception {
        WebApplicationContext ctx = getWebApplicationContext();
        UserManager mgr = (UserManager) ctx.getBean("userManager");
        return mapping.findForward("success");
    }
}



22 )   How to create PDF with Spring ?

Ans)

<?xml version="1.0" encoding="UTF-8"?>
    <bean name="*.pdf" class="common.PDFView">
    </bean>
</beans>

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.util.Map;
public class PDFView extends AbstractPdfView {
  private String filename;
  public String getFilename() {
    return filename;
  }
  public void setFilename(String filename) {
    this.filename = filename;
  }
  protected void buildPdfDocument(
          Map model,
          Document doc,
          PdfWriter writer,
          HttpServletRequest req,
          HttpServletResponse resp)
          throws Exception {
    PdfContentByte cb = writer.getDirectContent();
    PdfReader reader = new PdfReader(new FileInputStream(filename));
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
      doc.newPage();
      PdfImportedPage page = writer.getImportedPage(reader, i);
      cb.addTemplate(page, 0, 0);
    }
  }

  protected Document newDocument() {
    return new Document();
  }
}





23 )   How to use Spring in a Servlet Based Web Application ?

Ans)
Java Code:
ApplicationContext beanFactory =
WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());

Web.xml changes
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>



24 )    How to use JMS with Spring (JmsTemplate)

Ans)
public class JmsQueueSender {
  private JmsTemplate jmsTemplate;
  private Queue queue;
  public void setConnectionFactory(ConnectionFactory cf) {
    jt = new JmsTemplate102(cf, false);
  }
  public void setQueue(Queue q) {
    queue = q;
  }
  public void simpleSend() {
    this.jmsTemplate.send(this.queue, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage("hello queue world");
      }
    });
  }
}



25 )   How many way Spring Support Remote functionality ?

Ans)
Spring support Remoting several ways, but the following are important ones among them.
Remote Method Invocation (RMI). Through the use of the RmiProxyFactoryBean and the
RmiServiceExporter Spring supports both traditional RMI (with java.rmi.Remote interfaces
and java.rmi.RemoteException) and transparent remoting via RMI invokers.
Spring's HTTP invoker. Spring provides a special remoting strategy which allows for Java
serialization via HTTP, supporting any Java interface (just like the RMI invoker). The
corresponding support classes are HttpInvokerProxyFactoryBean and HttpInvokerServiceExporter.
JAX RPC. Spring provides remoting support for Web Services via JAX-RPC.
RMI:
<bean id="accountService" class="example.AccountServiceImpl">
    <!-- any additional properties, maybe a DAO? -->
</bean>
Next we'll have to expose our service using the RmiServiceExporter:
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
        <!-- does not necessarily have to be the same name as the bean to be exported -->
        <property name="serviceName" value="AccountService"/>
        <property name="service" ref="accountService"/>
        <property name="serviceInterface" value="example.AccountService"/>
        <!-- defaults to 1099 -->
        <property name="registryPort" value="1199"/>
</bean>

HTTPInvoker :
Server side :
<bean id="httpInvokerProxy" class="org.sprfr.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
  <property name="serviceUrl" value="http://remotehost:8080/AccountService"/>
  <property name="serviceInterface" value="example.AccountService"/>
</bean>
Client:
<property name="httpInvokerRequestExecutor"> <bean class="org.springframework.remoting.
httpinvoker.CommonsHttpInvokerRequestExecutor"/> </property>
Web Services:
Exposing services using JAX-RPC :
Spring has a convenience base class for JAX-RPC servlet endpoint implementations -
ServletEndpointSupport. To expose our AccountService we extend Spring's ServletEndpointSupport
class and implement our business logic here, usually delegating the call to the business layer
public class AccountServiceEndpoint extends ServletEndpointSupport
implements RemoteAccountService {
    private AccountService biz;
}
Accessing Web Services
<bean id="yourWebService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
        <property name="serviceInterface">
            <value>example.RemoteYourService</value>
        </property>
        <property name="wsdlDocumentUrl">
            <value>http://localhost:8080/your/services/yourService?WSDL</value>
        </property>
        <property name="namespaceUri">
            <value>http://localhost:8080/your/services/yourService</value>
        </property>
        <property name="serviceName">
            <value>yourService</value>
        </property>
        <property name="portName">
            <value>yourPort</value>
        </property>
    </bean>



26 )   Spring DWR example

Ans)
 Step 1 : Create a Service "YourPageManager" with different methods
  Step 2: Add the following Spring Config.
<dwr:remote javascript="YourPageManagerJS">
   <dwr:include method="getAccountSalesList"/>
   <dwr:include method="getEmailAddressByWebUserObjid"/>
   <dwr:include method="getStates"/>
   <dwr:include method="getTransportType"/>
   <dwr:include method="getContacts"/>
   <dwr:include method="findContacts"/>
   <dwr:filter class="com.your.ajax.DwrSecurityFilter"/>
  </dwr:remote>

    <dwr:configuration>
     <dwr:convert type="bean" class="com.yourApp.ContactDetails"
     javascript="Contact" />
 </dwr:configuration>
 <bean id="Contact" class="com.yourApp.ContactDetails">
 </bean>
Step 3 :
Add the following to JSP
Jsp changes :
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/util.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/YourPageManagerJS.js"></script>

YourPageManagerJS.addContactsToDTO(contactInfo, function(data){
    window.saveClicked = false;
    window.contactSaved = true;

       });



27 )   How to declare DispatcherServlet in Web.xml

Ans)

  • Spring DispatcherServlet set up
    Sample Img 27
The DispatcherServlet :
The DispatcherServlet is a central servlet that dispatches requests
to controllers, this plays the “Front Controller” role in Spring MVC. 
<web-app>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>
  org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>



29 )   Spring Command controllers Overview

Ans)
There are several types of Command controllers exist in Spring MVC including
"AbstractCommandController","SimpleFormController","AbstractWizardFormController"
each of these Controller offers different type of implementation capabilties.
Among these most commonly used one is "SimpleFormController", following code
 illustrates how to use this Controller.
This Controller offering form submission. The Controller class lets you specify
 a command object, a viewname for the form, a viewname for page you want to show
 the user when form submission has succeeded, and more.
Most important methods you should override when you use this Controller class are
 i) formBackingObject(HttpServletRequest httpServletRequest) :
  A method which you can use to set the New Form to your View.

 ii) Map referenceData():
     A method which you can use to pass model data to your view in the form of a Map;

 iii)
   onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse
     httpServletResponse, Object o, BindException e)

commandClass :
"commandClass" could be used to set your Form as following .
  <property name="commandClass" value="com.salesorder.StartForm"/>

commandName :
"commandName" with which you can