Explore model answers categorized by subjects like Java, HTML, DBMS, and more.
Spring is an open source framework, created by Rod Johnson. Spring is created to address the complexity of enterprise application development.
Spring makes it possible to use plain-vanilla JavaBeans to achieve things that were previously only possible with EJBs. However Spring\'s usefulness isn\'t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.
Spring is a lightweight container, with wrappers that make it easy to use many different services and frameworks. Lightweight containers accept any JavaBean, instead of specific types of components.
Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads.
The Spring framework is made up of seven well defined modules. These modules give you everything you need to develop enterprise-ready applications.
All of Spring\'s modules of are built on top of the core container. The container defines how beans are created, configured and managed-more of the nuts and bolts of Spring.
- The core container
- Application context module
- Spring\'s AOP module
- JDBC abstraction and DAO module
- Object/relation mapping integration module
- Spring\'s web module
- The Spring MVC framework
Inversion of control is at the heart of the Spring framework. The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework\'s IoC container.
The basic concept of the Inversion of Control pattern (dependency injection) is that programmers don\'t need to create your objects but describe how they should be created.
In a IOC scenario, the container creates all the objects, connects them together by setting the necessary properties, and determines when methods will be invoked.
The implementation pattern types for IOC used by SpringFramework are as follows:
Dependencies can be assigned through JavaBeans properties (setter methods).
Dependencies are provided as constructor parameters and are not exposed as JavaBeans Setter properties.
Aspect oriented programming is often defined as a programming technique that promotes separation of concerns within a software system.
Systems are composed of several components, each responsible for a specific piece of functionality.
AOP gives you aspects. Aspects enable modularization of concerns such as transaction management that cut across multiple types and objects.
AOP is used in the Spring Framework:
To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management.
To allow users to implement custom aspects, complementing their use of OOP with AOP.
The IoC (Inversion of Control) pattern uses three different approaches in order to achieve decoupling of control of services from your components:
Interface Injection : Your components explicitly conformed to a set of interfaces, with associated configuration metadata, in order to allow the framework to manage them correctly.
Setter Injection : External metadata is used to configure how your components can be interacted with.
Constructor Injection : Your components are registered with the framework, including the parameters to be used when the components are constructed, and the framework provides instances of the component with all of the specified facilities applied.
As J2EE containers, both Spring and EJB offer the developer powerful features for developing applications. Comparing the features:
Transaction management : EJB must use a JTA transaction manager and supports transactions that span remote method calls. Spring supports multiple transaction environment with JTA, Hibernate, JDO, JDBC, etc and does not support distributed transaction.
Declarative Transaction support : EJB can define transaction in deployment descriptor and can\'t derivatively define rollback behavior. Spring can define transaction in Spring configuration file and can declaratively define rollback behaviour per method and per exception type.
Persistence : EJB supports programmatic bean-managed persistence and declarative container managed persistence. Spring provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security : EJB supports declarative security through users and roles and configured in the deployment descriptor. In Spring, no security implementation out of the box. Acegi provides the declarative security framework built on the top of Spring.
Distributed computing : EJB provides container managed remote method calls. Spring provides proxying for remote calls via RMI, JAX-RPC, and web services.
A BeanFactory is an implementation fo the factory design patterns. The BeanFactory is a root interface for accessing a Spring bean container. This is the basic client view of a bean container; further interfaces such as ListableBeanFactory and ConfigurableBeanFactory are available for specific purposes.
This interface is implemented by objects that hold a number of bean definitions, each uniquely identified by a String name. Depending on the bean definition, the factory will return either an independent instance of a contained object.
The point of this approach is that the BeanFactory is a central registry of application components, and centralizes configuration of application components (no more do individual objects need to read properties files.
There are several implementations of BeanFactory in Spring. But the most useful is
org.springframework.beans.factory.xml.XmlBeanFactory, which loads its bean based on the definitions contained in an XML file.
BeanFactory f = new XmlBeanFactory(new FileInputStream(\"beans.xml\"));
You wire all of your bean's properties explicitly using theelement, However you can have Spring wire them automatically by setting the 'autowire' property on each that you want autowired: There are four types of autowiring: * byName :- Attempts to find a bean in the container whose name is the same as the name of the property being wired. * byType :- Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found, the property will not be wired. * constructor :- Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired. * autodetect :- Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring.
The various custom editors provided by the Spring Framework are: * PropertyEditor * URLEditor * ClassEditor * CustomDateEditor * FileEditor * LocaleEditor * StringArrayPropertyEditor * StringTrimmerEditor
All the Events are the subclasses of abstract class org.springframework.context.ApplicationEvent. These are: * ContextClosedEvent :- Published when the application context is closed. * ContextRefereshedEvent :- Published when the application context is initialized or refereshed. * RequestHandledEvent :- Published within a web application context when a request is handled. If you want a bean to respond to application events, all you need to do is implement the org.springframework.context.ApplicationListener interface. This interface forces your bean to implement the onApplicationEvent() method, which is responsible for reaching to the application event: public class RefreshListener implements ApplicaitonListener{ public void onApplicationEvent(ApplicationEvent e) { some code here// } You need to register it within the context:
We have two options that are available to integrate Struts application with Spring: * Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file. * Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.
Spring supports the following ORM’s : * Hibernate * iBatis * JPA (Java Persistence API) * TopLink * JDO (Java Data Objects) * OJB
An Advice is a Spring bean. Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints. An advice instance can be shared across all advised objects, or unique to each advised object. This corresponds to per-class or per-instance advice. Advice types in Spring: * Interception around advice * Before advice * Throws advice * After Returning advice * Introduction advice
Advisor is an aspect that contains just a single advice object associated with a pointcut expression. A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied. Any advisor can be used with any advice. The org.springframework.aop.support.DefaultPointcutAdvisor is the most commonly used advisor class. For example, it can be used with a MethodInterceptor, BeforeAdvice or ThrowsAdvice.
Spring defines pointcuts in terms of the class and method that is being advised. Advice is woven into the target class and its methods are based on their characteristics, such as class name and method signature. The core interface for Spring's pointcut framework is, naturally, the Pointcut interface.
Many terms used to define the AOP (Aspect Oriented Programming) features and they are part of the AOP language. These terms must be known to understand the AOP: * Aspect : An aspect is the cross-cutting functionality you are implementing. It is the aspect, or area of your application you are modularizing. The most common example of aspect is logging. Logging is something that is required throughout an application. * Joinpoint : A joinpoint is a point in the execution of the application where an aspect can be plugged in. * Advice : Advice is the actual implementation of our aspect. It is advising your application of new behaviour. * Pointcut : A pointcut defines at what joinpoints advice should be applied. * Introduction : An introduction allows you to add new methods or attributes to existing classes. * Target : A target is the class that is being advised. * Proxy : A proxy is the object created after applying advice to the target object. * Weawing : Weawing is the process of applying aspects to a target object to create a new proxied object.
Weaving is the process of applying aspects to a to a target object to create a new proxied object. The aspects are woven into the target object at the specified joinpoints. The weaving can take place at several points in the target class's lifetime: * Compile time : Aspects are woven in when the target class is compiled. This requires a special compiler. * Classload time : Aspects are woven at the time of loading of the target class into the JVM. It is done by ClassLoader that enhances that target class's bytecode before the class is introduced into the application. * Runtime : Sometimes aspects are woven in during the execution of the applicaion.
The interfaces that are used to create an Advice are: * org.aopalliance.intercept.MethodInterceptor * org.springframework.aop.BeforeAdvice * org.springframework.aop.AfterReturningAdvice * org.springframework.aop.ThrowsAdvice
Before the purchasing of our customer, we want to give them a warm greeting. For this, we need to add functionality before the method buySquishee() is executed. To accomplish this, we extend the MethodBeforeAdvice interface: public interface MethodBeforeAdvice{ void before(Method m, Object[] args, Object target) throws Throwable } This interface provides access to the target method, the arguments passed to this method, and the target object of the method invocation.
We want to make sure that we thank our patrons after they make their purchase. To do this, we implement AfterReturningAdvice: public interface AfterReturningAdvice{ void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable } } Like MethodBeforeAdvice, this advice gives you access to the method that was called, the arguments that were passed, and the target object.
The MethodInterceptor provides the ability to do both before advice and after advice in one advice object: public interface MethodInterceptor{ Object invoke(MethodInvocation invocation) throws Throwable; } There are two important difference between MethodInterceptor and the both before and after advice. First, the method interceptor implementation controls the target method invocation, and this invocation done by calling MethodInvocation.proceed(). Second, MethodInterceptor gives you control over what object is returned.
The RegexpMethodPointcut lets you leverage the power of regular expressions to define your pointcuts. It uses Perl-style regular expressions to define the pattern that should match your intended methods. Common regular expression symbol used are (.) matches any single character, (+) Matches the preceding character one or more times, (*) matches the preceding character zero or more, (\) Escapes any regular expression symbol. For Example: If we want to match all the setXxx methods, we need to use the pattern .*set.* (the first wildcard will match any preceding class name.
The Introductions are little different from Spring advice. Advice are woven at different jointpoints surrounding a method invocation. Introductions affect an entire class by adding new methods and attributes to the adviced class. Introductions allow you to build composite objects dynamically, affording you the same benefits as multiple inheritance. Introductions are implemented through IntroductionMethodInterceptor, a subinterface of MethodInterceptor. This method adds one method: boolean implementsInterface(Class intf); This method returns true if the IntroductionMethodInterceptor is responsible for implementing the given interface.
ProxyFactoryBean creates proxied objects. Like other JavaBeans, it has properties that control its behaviour. ProxyFactoryBean properties are: * target : The target bean of the proxy. * proxyInterface : A list of interfaces that should be implemented by the proxy. * interceptorNames : The bean names of the advice to be applied to the target. * singleton : Whether the factory should return the same instance of the proxy for each getBean invocation. * aopProxyFactory : The implemetation of the ProxyFactoryBean interface to be used. * exposeProxy : Whether the target class should have access to the current proxy. This is done by calling AopContext.getCurrentProxy. * frozen : Whether changes can be made to the proxy's advice once the factory is created. * optimize : Whether to aggressively optimize generated proxies. * proxyTargetClass : Whether to proxy the target class, rather than implementing an interface.
Spring has a facility of autoproxy that enables the container to generate proxies for us. We create autoproxy creator beans. Spring provides two classes to support this: * BeanNameAutoProxyCreator * DefaultAdvisorAutoProxyCreator
BeanNameAutoProxyCreator generates proxies for beans that match a set of names. This name matching is similar to the NameMethodMatcherPointcut which allows for wildcard matching on both ends of the name. This is used to apply an aspect or a group of aspects uniformly across a set of beans that follow a similar naming conventions. The DefaultAdvisorAutoProxyCreator is the more powerful autoproxy creator. Use this class to include it as a bean in your BeanFactory configuration. It implemnts the BeanPostProcessor interface. DefaultAdvisorAutoProxyCreator only works with advisors.
Spring also supprts autoproxying driven by metadata. Metadata autoproxy configuration is determined by source level attributes and keeps AOP metadata with the source code that is being advised. This lets your code and configuration metadata in one place. The most common use of metadata autoproxying is for declarative transaction support.
Spring Framework's Data Access Object (DAO) support provides integration of heterogeneous Java Database Connectivity (JDBC) and Object-Relational Mapping (ORM) products. DAO support is provided for JDBC, Hibernate, iBATIS, Java Data Objects (JDO), Java Persistence API (JPA), Oracle's TopLink and Common Client Interface (CCI).
Spring's org.springframework.dao.DataAccessException extends the extends NestedRuntimeException which in turn extends and RuntimeException. Hence DataAcccessException is a RuntimeException so there is no need to declare it in the method signature.
Springs's DAO exception hierarchy is : * CleanupFailureAccessException * DataAccessResourceFailureException * DataIntegrityViolationException * DataRetrievalFailureException * DeadlockLoserDataAccessException * IncorrectUpdateSemanticsDataAccessException * InvalidDataAccessApiUsageException * InvalidDataAccessResourceUsageException * OptimisticLockingFailureException * TypeMismatchDataAccessException * UncategorizedDataAccessException
The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions defined in the hierarchy of org.springframework.dao package. Code using the JdbcTemplate only need to implement callback interfaces, giving them a clearly defined contract. The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class, providing SQL and any necessary parameters. The JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource reference, or be configured in a Spring IOC container and given to DAOs as a bean reference. Example: JdbcTemplate template = new JdbcTemplate(myDataSource); A simple DAO class looks like this. public class StudentDaoJdbc implements StudentDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } // more code here }
The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters (as opposed to programming JDBC statements using only classic placeholder ('?') arguments. The NamedParameterJdbcTemplate class wraps a JdbcTemplate, and delegates to the wrapped JdbcTemplate to do much of its work.
the JDBC Core classes to control basic JDBC processing and error handling in Spring's JDBC API are : * JdbcTemplate * NamedParameterJdbcTemplate * SimpleJdbcTemplate (Java5) * DataSource * SQLExceptionTranslator
The classes that are used to Control the database connection in Spring's JDBC API are : * DataSourceUtils * SmartDataSource * AbstractDataSource * SingleConnectionDataSource * DriverManagerDataSource * TransactionAwareDataSourceProxy * DataSourceTransactionManager
Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.
To configure your database driver using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". For Example:org.hsqldb.jdbcDriver jdbc:hsqldb:db/appfuse sa
You can configure JNDI instead of datasource in spring applicationcontext.xml using "org.springframework.jndi.JndiObjectFactoryBean". For Example:java:comp/env/jdbc/appfuse
To create a DataSource connection pool :${db.driver} ${db.url} ${db.username} ${db.password}
BatchPreparedStatementSetter interface sets values on a PreparedStatement provided by the JdbcTemplate class for each of a number of updates in a batch using the same SQL. Implementations are responsible for setting any necessary parameters. SQL with placeholders will already have been supplied. Implementations of BatchPreparedStatementSetter do not need to concern themselves with SQLExceptions that may be thrown from operations they attempt. The JdbcTemplate class will catch and handle SQLExceptions appropriately. BatchPreparedStatementSetter has two method: * int getBatchSize() :- Return the size of the batch. * void setValues(PreparedStatement ps, int i) :-Set values on the given PreparedStatement.
RowCallbackHandler interface is used by JdbcTemplate for processing rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of processing each row but don't need to worry about exception handling. SQLExceptions will be caught and handled by the calling JdbcTemplate. RowCallbackHandler object is typically stateful: It keeps the result state within the object, to be available for later inspection. RowCallbackHandler interface has one method : void processRow(ResultSet rs) :- Implementations must implement this method to process each row of data in the ResultSet.