Spring JDBC with Hibernate

June 27, 2008 by lequangminh04

Introducing Spring’s ORM framework support
               When we were kids, riding a bike was fun, wasn’t it? We would ride to school in the mornings. When school let out we would cruise to our best friend’s house. When it got late and our parents were yelling at us for staying out past dark, we would peddle home for the night. Gee, those days were fun.But then we grew up and we needed more than a bike. Sometimes we have to travel quite a distance to work. Groceries have to be hauled and ours kids need to get to soccer practice. And if you live in Texas, air conditioning is a must! Our needs have simply outgrown our bike. JDBC is the bike of the persistence world. It is great for what it does, and for some jobs it works just fine. But as our applications become more complex, so do our persistence requirements. We need to be able to map object properties to database columns and have our statements and queries created for us, freeing us from typing an endless string of question marks. We also need more sophisticated features such as the following:
            ■ Lazy loading—As our object graphs become more complex, we sometimes don’t want to fetch entire relationships immediately. To use a typical example, suppose we are selecting a collection of PurchaseOrder objects, and each of these objects contains a collection of LineItem objects. If we are only interested in PurchaseOrder attributes, it makes no sense to grab the LineItem data. This could be quite expensive. Lazy loading allows us to grab data only as it is needed.
            ■ Eager fetching—This is the opposite of lazy loading. Eager fetching allows you to grab an entire object graph in one query. So if we know we need a PurchaseOrder object and its associated LineItems, eager fetching lets us get this from the database in one operation, saving us from costly round-trips.
           ■ Caching—For data that is read-mostly (used often but changed infrequently), we don’t want to fetch this from the database every time it is used.
Caching can add a significant performance boost.
            ■ Cascading—Sometimes changes to a database table should result in changes to other tables as well. Going back to our purchase order example, it is reasonable that a LineItem object has an association with a Product object. In the database, this is most likely represented as a many-to-many relationship. So when a LineItem object is deleted, we also want to disassociate this LineItem from its Product object in the database. Fortunately, there are frameworks out there that already provide these services. The general term for these services is object/relational mapping (ORM). Using an ORM tool for your persistence layer can save you literally thousands of lines of code and hours of development time. This lets you switch your focus from writing
error-prone SQL code to addressing your application requirements. Spring provides integration for Sun’s standard persistence API JDO, as well as
the open source ORM frameworks Hibernate, Apache OJB, and iBATIS SQL Maps. Spring’s support for each of these technologies is not as extensive as its JDBC support. This is not a poor reflection on Spring’s APIs, but rather a testament to how much work each of these ORM frameworks does. With the ORM tool doing most of the actual persistence, Spring provides integration points to these frameworks, as well as some additional services:
            ■ Integrated transaction management
            ■ Exception handling
            ■ Thread-safe, lightweight template classes
            ■ Convenience support classes
            ■ Resource management
        While we are going to cover Spring’s integration with all four of these ORM frameworks, we will not go into the details of each specific framework. We will give an explanation of their general behavior and some example configurations. If you want to explore any of these frameworks in detail, a wealth of resources is available.
4.4 Integrating Hibernate with Spring
Hibernate is a high-performance, open source persistence framework that has gained significant popularity recently. It provides not only basic object/relational mapping but also all the other sophisticated features you would expect from a full-featured ORM tool, such as caching, lazy loading, eager fetching, and distributed caching. You can learn more about it in Hibernate in Action from Manning or at the Hibernate web site http://www.hibernate.org.
4.4.1 Hibernate overview
You configure how Hibernate maps your objects to a relational database through XML configuration files. For an example of how this is done, let’s examine how we would map the Student class from our Spring Training application. First, let’s examine the Student class, shown in listing 4.12.   Student.java
import java.util.Set;
public class Student {
         private Integer id;
         private String firstName;
         private String lastName;
         private Set courses;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() { return lastName; }
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set getCourses() { return courses; }
public void setCourses(Set courses) { this.courses = courses; }
}

Typically, each persistent class will have a corresponding XML mapping file that ends with the extension “.hbm.xml.” Let’s take a look at the mapping file for the Student class. By convention, we would name this file Student.hbm.xml, which is shown in listing 4.13.

Listing 4.13 Student.hbm.xml Hibernate mapping file

<?xml version=”1.0″?>

<!DOCTYPE hibernate-mapping

PUBLIC “-//Hibernate/Hibernate Mapping DTD//EN”

“http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd”>

<hibernate-mapping>

      <class name=”org.springinaction.training.model.Student”>

             <id name=”id”>

            <generator class=”assigned”/>

 

              </id>

 

            

              <property name=”sex”/> 

 

             <property name=”weight”/>

             <set name=”courses” table=”transcript”>

                  <key column=”student_id”/>

                    <many-to-many column=”course_id”

                       class=”org.springinaction.training.model.Course”/>

             </set>

</class>

</hibernate-mapping>

 

 

       In a typical application, you will have several of these files. These configuration files are then read in to create a SessionFactory. A SessionFactory will last the lifetime of your application and you will use it to obtain (what else?) Session objects. It is with these Session objects that you will access the database. So assuming that we have a configured SessionFactory, here is how we would get a Student object by its primary key:
     public Student getStudent(Integer id) throw HibernateException {
            Session session = sessionFactory.openSession();
            Student student = (Student) session.load(Student.class, id);
             session.close();
             return student;
      }

      This is a trivial example of using Hibernate that excludes exception handling. But there is one thing you should take from this: Very little code is required to execute this operation. In fact, we actually load the Student object in one line of code. This is because Hibernate is doing all the work based on your mappings. Since Hibernate is taking care of making persistence easier, Spring focuses on making it easier to integrate with Hibernate. Let’s look at some of the ways Spring does this.

4.4.2 Managing Hibernate resources
As we said, you will keep a single instance of a SessionFactory throughout the life of your application. So it makes sense to configure this object through your Spring configuration file. You do so using the Spring class LocalSessionFactoryBean:

Of course the SessionFactory needs to know to which database to connect. The preferred way to do this is to wire a DataSource to the LocalSessionFactoryBean:

<bean id=”dataSource”

       class=”org.springframework.jndi.JndiObjectFactoryBean”>

        <property name=”jndiName”>

            <value>java:comp/env/jdbc/trainingDatasource</value>

        </property>

</bean>

<bean id=”sessionFactory” class=”org.springframework. orm.hibernate.LocalSessionFactoryBean”>

        <property name=”dataSource”>

            <ref bean=”dataSource”/>

         </property>

 

 

      You also manage how Hibernate is configured through the same LocalSession- FactoryBean bean. Hibernate itself has dozens of properties by which you can tweak its behavior. When used outside of Spring, Hibernate looks for a file named hibernate.properties somewhere on the application class path for its configurations. However, with Spring you do not have to manage these configurations in a separate properties file. Instead, you can wire them to the hibernateProperties property of the LocalSessionFactoryBean:

<bean id=”sessionFactory” class=”org.springframework. orm.hibernate.LocalSessionFactoryBean”>

         <property name=”hibernateProperties”>

            <props>

                   <prop key=”hibernate.dialect”>net.sf.hibernate.dialect.MySQLDialect</prop>

            </props>

         </property>

</bean>

 

 

One last thing you must configure is which mapping files Hibernate should read in. Remember when we created a Student.hbm.xml file? Well, we actuallyhave to tell Hibernate it needs to use this file. Otherwise it will not know how to
map the Student class to the database. Again, we can configure this through a property of the LocalSessionFactoryBean bean. In this case, we use the mapping- Resources property:

 

 

<bean id=”sessionFactory” class=”org.springframework. orm.hibernate.LocalSessionFactoryBean”>

       <property name=”mappingResources”>

 

 

           <list> 

 

               <value>Student.hbm.xml</value>

               <value>Course.hbm.xml</value>

           </list>

        </property>

</bean>

 

        This example works just fine for our small Spring Training application. But what  happens if your application grows and you have dozens, if not hundreds, of persistent classes? It would be cumbersome to configure them all in this fashion. Fortunately, Spring offers you an alternative. You can also configure the mapping- DirectoryLocations property with a path that is a subset of your application’s class path, and Spring will configure the SessionFactory with every *.hbm.xml it finds in this path. For example, assuming that all the persistent classes we want to configure are contained in the com.springinaction.training.model package, we would configure our SessionFactory like this:

 

 <bean id=”sessionFactory” class=”org.springframework.orm.hibernate.LocalSessionFactoryBean”> 

     <property name=”mappingDirectoryLocations”>

     <list>

           <value>classpath:/com/springinaction/training/model</value>

      </list>

</property>

</bean>

 

     Now we have a fully configured SessionFactory and we didn’t even need to create a second configuration file. Now all we need to do is create an object through which we will access Hibernate. Like all of Spring’s DAO frameworks, this will be a template class. In this case, it is the HibernateTemplate class. And because the HibernateTemplate class is thread-safe, we can share this template class with multiple DAO objects:

 

<bean id=”hibernateTemplate” class=”org.springframework.orm.hibernate.HibernateTemplate”>

      <property name=”sessionFactory”>

           <ref bean=”sessionFactory”/>

       </property>

</bean>

<bean id=”studentDao” class=”com.springinaction.training.dao.hibernate.StudentDaoHibernate”>

       <property name=”hibernateTemplate”>

            <ref bean=”hibernateTemplate”/> 

 

       </property> 

 

</bean>

<bean id=”courseDao” class=”com.springinaction.training.dao.hibernate.CourseDaoHibernate”>

      <property name=”hibernateTemplate”>

           <ref bean=”hibernateTemplate”/>

      </property>

</bean>

 

          And remember, if it becomes cumbersome to wire the template into each of your DAO beans, you can always use Spring’s autowire facility to implicitly wire your DAO beans. Now that you know how to wire a HibernateTemplate to your DAO objects, we are ready to start using Hibernate.

4.4.3 Accessing Hibernate through HibernateTemplate
           The template-callback mechanism in Hibernate is pretty simple. There is theHibernateTemplate and one callback interface: HibernateCallback. And the HibernateCallback interface has just one method:

           Object doInHibernate(Session session) throws HibernateException, SQLException;
          As you can see, the HibernateCallback interface is pretty straightforward. Now, let’s put the HibernateTemplate to use. We’ll begin by getting an object from the database:
         public Student getStudent(final Integer id) {
                  return (Student) hibernateTemplate.execute(
                                           new HibernateCallback() {
                                                   public Object doInHibernate(Session session)  throws HibernateException {
                    return session.load(Student.class, id);
                                                                                    }  });
          }
            Since we are using an inner class, a little more code is required and is not quite as clean as when we were not using Spring’s Hibernate support. But we can have it both ways—clean code and Spring Hibernate support. The HibernateTemplate class provides some convenience methods that implicitly create a HibernateCallback instance for you. All you have to do is call one of the convenience methods and Spring’s framework does the rest. For example, here is how you would take advantage of one of these methods to accomplish the exact same thing as we did earlier—get an object from the database:
        public Student getStudent(Integer id) {
                  return (Student) hibernateTemplate.load(Student.class, id);
         }
         Now we are getting somewhere! We now have the benefits of having Spring managing our resources, converting proprietary exceptions, and, if we choose, adding transactions. The previous example is how you will access Hibernate through the Hibernate template the majority of the time. The HibernateTemplate class contains a wealth of convenience methods for you to use. For example, to update a Student object, this is all that would be required:
       public void updateStudent(Student student) {
                    hibernateTemplate.update(student);
         }
         Executing queries is not that much different. All we need to do is specify the query (usually in Hibernate’s query language, HQL). Querying for students by last name would look something like this:
       public List findStudentsByLastName(String lastName) {
                return hibernateTemplate.find(“from Student student ” +  “where student.lastName = ?”,  lastName, Hibernate.STRING);
       }

        Pretty straightforward, right? Even if you have never seen HQL before, this
code should be easy to follow. As we said before, Spring’s framework makes for easy integration.

4.4.4 Subclassing HibernateDaoSupport :

          Spring’s Hibernate ORM framework also comes with the convenience class HibernateDaoSupport that your DAO classes can subclass:
           public class StudentDaoHibernate extends HibernateDaoSupport implements StudentDao {
              …
            }

          If you opt for this design, you need to wire in a SessionFactory—the Hibernate-DaoSupport class comes with this property. This class provides you with a convenience method, getHibernateTemplate(), to easily get an instance of a HibernateTemplate. It also has a getSession() and a closeSessionIfNecessary() method if, for some reason, you need to perform a Hibernate operation without using a Hibernate- Template. We are sure you will find these cases will be the exception (no pun intended). So now you can see how easily you can integrate an ORM tool like
Hibernate. We think you will find the JDO integration just as easy.

 

Developing with POJO (part-2)

June 26, 2008 by lequangminh04

back
Using POJOs
Once you break free of the constraints imposed by the EJB 2 programming model, implementing the object model shown in figure 1.2 is easy. Java provides all of the necessary features, including fine-grained objects, relationships, inheritance, and recursion. It is straightforward to implement expressive object models like this one using POJOs and thus benefit from improved maintainability and testability. Java is an object-oriented language, so it is foolish not to use its capabilities.

As a bonus, POJOs have these other important benefits:

Easier development—There is less cognitive load because rather than being forced to think about everything—business logic, persistence, transactions etc.—at once you can instead focus on one thing at a time. You can first design and implement the business logic and then, once that is working, you can deal with persistence and transactions.
Faster development—You can develop and test your business logic outside of the application server and without a database. You do not have to package your code and deploy it in the application. Also, you do not have to keep the database schema constantly in sync with the object model or spend time waiting for slow-running database tests to finish. Tests can run in a few seconds and development can happen at the speed of thought—or at least as fast as you can type!
Improved portability—You are not tied to a particular implementation technology. The cost of switching to the next generation of Java technology is minimized because you have to rewrite only a small amount of code, if any.
I was genuinely surprised by how POJOs changed how I went about development because I’d become so accustomed to the cumbersome EJB approach. As with the TiVo box I described earlier, I had to use them before I appreciated their true value. But now I couldn’t imagine reverting to the old way of working. Of course, you still need to handle persistence and transactions, which is where lightweight frameworks come in.

Persisting POJOs
When the time comes to persist the POJOs that implement the business logic, there are some powerful object/relational mapping frameworks to choose from. The main ones are JDO, which is a standard from Sun, and Hibernate, which is an extremely popular open source framework. In addition, the specification for EJB 3 entity beans appears to be potentially quite powerful.

Transparent persistence with JDO and Hibernate

JDO and Hibernate provide transparent persistence, which means that the classes are unaware that they are persistent. The application just needs to call the persistence framework APIs to save, query, and delete persistent objects. The persistence framework automatically generates the SQL statements that access the database using an object/relational mapping, which is defined by XML documents or Java 5 annotations. The object/relational mapping specifies how classes map to tables, fields map to columns, and relationships map to either foreign keys or join tables. JDO and Hibernate can also run outside of the application server, which means that you can test your persistent business logic without deploying it in a server. You can, for example, simply run tests from within your integrated development environment (IDE).

Encapsulating the calls to the persistence framework

Even though Hibernate and JDO provide transparent persistence, some parts of an application must call the JDO and Hibernate APIs to save, query, and delete persistent objects. For example, TransferService must call the persistence framework to retrieve the accounts and create a BankingTransaction. One approach is for TransferService to call the persistence framework APIs directly. Unfortunately, this would couple TransferService directly to the persistence framework and the database, which makes development and testing more difficult.

A better approach is to encapsulate the Hibernate or JDO code behind an interface, as shown in figure 1.2. The persistence framework, which in this example is Hibernate, is encapsulated by the repository classes. Each repository consists of an interface and a Hibernate implementation class and is responsible for one type of object. The JDO implementation would be similar.

Click here for a larger image.

Figure 1.2 Using repositories to encapsulate the persistence framework hides the persistence details from the rest of the application.

In this example, repositories call the Hibernate APIs to access the database. AccountRepository finds accounts and BankingTransactionRepository creates BankingTransactions. The TransferService is written in terms of the AccountRepository and BankingTransactionRepository interfaces, which decouples it from the persistence framework and the database. By the intelligent use of interfaces, you can avoid coupling your domain logic to a particular persistence framework. This will enable you to test the domain model without the database, which simplifies and accelerates testing. It also enables you to use a different persistence framework if your needs change. For example, changing this application from Hibernate to JDO or even EJB 3 is simply a matter of changing the concrete classes that access the persistence framework. It’s a generally accepted observation that loosely coupled applications are easier to maintain and test.

Developing with POJO

June 26, 2008 by lequangminh04

Developing with POJOs
By Chris Richardson

next

Long before the EJB 3 specification was written, some developers disillusioned with EJB started to look for alternative frameworks. POJOs are an especially compelling alternative to EJBs. A POJO is simply a Java object that does not implement any special interfaces such as those defined by the EJB framework. The name was coined by Fowler, Rebbecca Parsons, and Josh MacKenzie [Fowler POJO] to give regular Java objects an exciting-sounding name. Later in this section you will see how this simple idea has some surprisingly important benefits.

However, POJOs by themselves are insufficient. In an enterprise application you need services such as transaction management, security, and persistence, which were previously provided by the EJB container. The solution is to use the increasingly popular so-called “lightweight” frameworks that replace some “heavyweight” parts of the J2EE stack. They do not completely replace the J2EE stack but can be used in combination with some parts of it to provide important enterprise services.

The four lightweight frameworks that I describe in this book are Hibernate, JDO, iBATIS, and Spring. Except for JDO, which is a specification, they are open source projects, which have helped drive the adoption of POJOs and lightweight frameworks by the community. Hibernate and JDO are persistence frameworks, which map POJOs to a relational database. They are layered on top of JDBC and significantly increase developer productivity. iBATIS is also layered on top of JDBC, but it maps POJOs to SQL statements and is a very convenient way to execute SQL statements. The Spring framework has a wide range of features that make it easier to use than EJB, including the equivalent of container-managed transactions for POJOs.

An important feature of these technologies is that they are nonintrusive. Unlike EJBs, they provide transactions and persistence without requiring the application classes to implement any special interfaces. Even when your application’s classes are transactional or persistent, they are still POJOs, which means that you continue to experience the benefits of POJOs that I describe in this article.

Some excellent books are available that describe these frameworks in depth: Hibernate in Action [Bauer 2005], Spring in Action [Walls 2005], iBATIS in Action [Begin, forthcoming], and Java Data Objects [Russell 2003]. You do not need to read these books to understand and benefit from this book. But to apply what you learn here you do need to read them to learn the details.

In this section I will provide an overview of how to use POJOs and lightweight frameworks to redesign the money transfer service and make it easier to develop, test, and maintain. This new design is object-oriented POJO-based instead of a procedural EJB-based. It accesses the database using a persistence framework that is layered on top of JDBC instead of using JDBC directly. The business logic is encapsulated by a POJO façade instead of a session bean, and transactions are managed by the Spring framework instead of the EJB container. The business logic returns real business objects to the presentation tier instead of DTOs. The application is assembled by passing a component’s dependencies as setter or constructor arguments instead of the component using Java Naming and Directory Interface (JNDI) lookups. Because the design is object-oriented and uses these lightweight technologies, it is much more developer-friendly than the EJB version we saw earlier.

Table 1.1 summarizes the differences between the two designs.

Table 1.1 Comparing classic EJB and POJO approaches

Classic EJB approach POJO approach
Organization Procedural-style business logic Object-oriented design
Implementation EJB-based POJOs
Database access JDBC/SQL or Entity beans Persistence framework
Returning data to the presentation tier DTOs Business objects
Transaction management EJB container-managed transactions Spring framework
Application assembly Explicit JNDI lookups Dependency injection

Don’t worry if you are not familiar with all of these terms. In this section, I’ll examine each difference and explain and justify the POJO approach. You will see how to develop business logic using the POJO approach. I use the money transfer application from section 1.1.2 as an example.

Using an object-oriented design
Rather than structuring the money transfer example around methods such as transfer() and its helper methods, the code should be structured around an object model, which is a collection of classes that typically corresponds to realworld concepts. For example, in the money transfer application, the object model consists of classes such as Account, OverdraftPolicy, and BankingTransaction. In addition, there is a TransferService that coordinates the transfer of money from one account to another. Figure 1.1 shows the design.

Click here for a larger image.

Figure 1.1 An object model for the money transfer application

An Account maintains its balance and has an OverdraftPolicy, which determines what happens when the account is about to become overdrawn. OverdraftPolicy is an example of a Strategy pattern [Gang of Four] and there are two implementations of OverdraftPolicy: one for each type of real-world policy. Better yet, an OverdraftPolicy could encapsulate a rules engine and thereby enable the business rules for overdrafts to be changed dynamically. TransferTransaction, which is a subclass of BankingTransaction, records the transfer of money between two accounts.

Using an object-oriented design has a number of benefits. First, the design is easier to understand and maintain. Instead of consisting of one big class that does everything, it consists of a number of small classes that each have a small number of responsibilities. In addition, classes such as Account, BankingTransaction, and OverdraftPolicy closely mirror the real world, which makes their role in the design easier to understand.

Second, our object-oriented design is easier to test: each class can and should be tested independently. For example, we could write unit tests for Account and for each implementations of OverdraftPolicy. In comparison, an EJB can only be tested by calling its public methods, for example, transfer(), which is a lot more difficult. You can only test the complex functionality exposed by the public methods rather than test the simpler pieces of the design.

Finally, the object-oriented design in figure 1.2 is easier to extend because it can use well-known design patterns, such as the Strategy pattern and the Template Method pattern [Gang of Four]. Adding a new type of overdraft policy simply requires defining a new subclass of OverdraftPolicy. By contrast, extending an EJB-style procedural design usually requires changing the core code, and rewriting or chaining procedure calls together.

As you can see, our object-oriented design has some important benefits. But it is essential to know when it is not a good choice.

C#

June 26, 2008 by lequangminh04

C#

Spring Framework Overview

June 24, 2008 by lequangminh04

1.  What is IOC (or Dependency Injection)?

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.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

 

2. What are the different types of IOC (dependency injection) ?

 

There are three types of dependency injection:

  • 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. Note: Spring supports only Constructor and Setter Injection

 

 

3. What are the benefits of IOC (Dependency Injection)?

Benefits of IOC (Dependency Injection) are as follows:

  • Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.

  • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.

  • Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.

  • IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

 

4.  What is Spring ?

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

5. What are the advantages of Spring framework?

The advantages of Spring are as follows:

  • 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.

 

6. What are features of Spring ?

  • spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.

  • Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

  • Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

  • Spring contains and manages the life cycle and configuration of application objects.

  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.

  • Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring’s transaction support is not tied to J2EE environments and it can be also used in container less environments.

  • The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

 

7. How many modules are there in Spring? What are they?

      Spring comprises of seven modules. They are..

  • The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code. 

  • The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. 

  • The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. 

  • The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy. 

  • The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies. 

  • The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. 

  • The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. 

8. What are the types of Dependency Injection Spring supports ?

  • Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

  • Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborato

9. What is Bean Factory ?

A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.

  • BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
  • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

10. What is Application Context?

A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:

  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.

11. What is the difference between Bean Factory and Application Context ?  

On the surface, an application context is same as a bean factory. But application context offers much more..

  • Application contexts provide a means for resolving text messages, including support for i18n of those messages. 
  • Application contexts provide a generic way to load file resources, such as images. 
  • Application contexts can publish events to beans that are registered as listeners. 
  • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. 
  • ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances. 
  • MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable