Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/vir007/public_html/geekmantra.com/contact/connect.php on line 2
Free Online Spring Examples Tutorials in Springs,Spring Examples in Springs
GeekMantra
Search Site

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/vir007/public_html/geekmantra.com/contact/connect.php on line 2
J2SE [Java 2 Standard Edition]
Core Java Introduction
Exception Handling
Collection & Util Classes
Multithreading
Input & Output Streams
Applet
Adwance Windows Toolkit (AWT)
Swings (Adwance GUI)
Event Handling
Java Networking
Remote Method Invocation (RMI)
Java Database Connectivity (JDBC)
J2EE [Java 2 Enterprise Edition]
Java 2 Enterprise Edition Intoduction (J2EE)
Server Side Programming (Servlet)
Java Server Pages (JSP)
Enterprise Java Bean
MVC Framework (Struts)
Advance Framework (Springs)
Object-relational mapping (Hibernate)
eXtensible Markup Language (XML)
Asynchronous JavaScript and XML (AJAX)
Miscellneous
Monthly News Letter
Free SCJP Samples
Interviews Questions For Freshers
Interviews Questions For Experinced
Most Visited Links
Most Freaky Links
Advertisements

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/vir007/public_html/geekmantra.com/contact/connect.php on line 2

HelloWorld Example in Spring


Step 1 –
Unzip spring-framework-1.2.7-with-dependencies.zip

Inside the folder spring12 we can find 7 folders,
1. dist: It contains various Spring distribution jar files.
2. docs: It contains general documentation and API javadocs.
3. mock: It contains mock JNDI contexts and a set of servlet API mock objects.
4. samples: It contains demo applications and skeletons.
5. src: It contains the Java source files for the framework.
6. test: It contains the Java source files for Spring`s test suite.
7. tiger: It contains JDK1.5 examples and test suite.

Inside the "dist" directory, we can find all the jar files necessary for compiling and executing the program. The
jar files and its contents are listed below:
1. spring.jar : It contains the entire Spring framework including everything in the other JAR files also.
2. spring-core.jar : It contains the core Spring container and its utilities.
3. spring-beans.jar : It contains the bean Spring container and JavaBeans support utilities.
4. spring-aop.jar : It contains Spring`s AOP framework, source-level metadata support, AOP Alliance
interfaces etc.,
5. spring-context.jar : It contains application context, validation framework, JNDI, template support and
scheduling.
6. spring-dao.jar : It contains DAO support and transaction infrastructure.
7. spring-jdbc.jar : It contains the JDBC support.
8. spring-support.jar : It contains JMX support, JCA support, scheduling support, mail support and caching
support.
9. spring-web.jar : It contains the web application context, multipart resolver, Struts support, JSF support and
web utilities.
10. spring-webmvc.jar : It contains the framework servlets, web MVC framework, web controllers and web
views.
11. spring-remoting.jar :It contains remoting support, EJB support and JMS support.
12. spring-orm.jar : It contains iBATIS SQL Maps support, Apache OJB support, TopLink support and JDO
support.
13. spring-hibernate.jar : It contains Hibernate 2.1 support, Hibernate 3.x support.
14. spring-mock.jar : It contains JNDI mocks, Servlet API mocks and JUnit support

Step 2 – In Eclipse start a Java project say HelloSpring, add following two jar in project build path, spring.jar
and common-logging.jar (take it from tomcat).

    For a typical Spring Application we need the following files
    2.1 An interface that defines the functions. (optional but recommended)
    2.2 An Implementation that contains properties, its setter and getter methods, functions etc.,
    2.3 A XML file called Spring configuration file.
    2.4 Client program that uses the function.

2.1 HelloI.java
package org.test;
    public interface HelloI {
        String sayHello(String msg);
    }

2.2 HelloImpl.java
package org.test;
    public class HelloImpl implements HelloI {
        private String msg = "Hello ";
        public HelloImpl() {
        }
    public String sayHello(String msg) {
        return msg + this.msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

2.3 hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/springbeans.
dtd">
<beans>
    <bean id="hello" class="org.test.HelloImpl">
    <property name="msg">
        <value> Sumit!!</value>  property injection
    </property>
    </bean>
</beans>

2.4 Client.java
package org.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class HelloClient {
    public static void main(String args[]) throws Exception {
        try {
            System.out.println("please Wait......");
            Resource res = new ClassPathResource("hello.xml");
            BeanFactory factory = new XmlBeanFactory(res);
            HelloI h = (HelloI) factory.getBean("hello");
            String s = h.sayHello("hi");
            System.out.println(s);
        } catch (Exception e1) {
        e1.printStackTrace();
        }
        }
    }

Output -

please Wait......
Apr 2, 2006 7:33:52 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [hello.xml]
hi Sumit!!

The container instantiates the `HelloImpl` based on the XML definition as,

    HelloImpl h = new HelloImpl();
    helloimpl.setGreeting("Sumit!!");


Similarly, greeting property may be set through the single argument constructor of `HelloImpl` as,

<bean id="hello" class="HelloImpl">
<constructor-arg> constructor injection
<value>Good Morning!...</value>
</constructor-arg>
</bean>

hello world spring

Spring doesn`t give you a servlet container. Instead, it just gives you a set of services that make it easier to build
web applications.

Most projects simply don`t need a full-blown J2EE container. One of the best things about Spring is that you
can deploy it, in production, without paying for an application server, or the hardware that you`d need to run
one. Tomcat will manage your servlets, provide an easy architecture for managing deployments, and let you
manage its threading model

Understanding Aspect-Oriented Programming

It is a new programming technique that promotes separation of concerns within the system.

While inversion of control makes it possible to tie software components together loosely, aspect-oriented
programming enables you to capture functionality that is used throughout your application in reusable
components

System are composed of several components each responsible for a specific piece of functionality. Whatever
may be the core function of the program, the system service like logging, transaction management, security etc.,
must be included in the program. These system services are commonly referred to as `cross-cutting concerns`
as they tend to cut across multiple components in a system. AOP makes it possible to modularize and separate
these services and then apply them declaratively to the components and we can focus on our own specific
concerns. In spring, aspects are wired into objects in the spring XML file in the same way as JavaBean. This
process is known as `Weaving`.

Spring

Bad - The business objects on the left are too intimately involved with the system services. Not only does each
object know that it is being logged, secured, and involved in a transactional context, but also each object is
responsible for performing those services for itself.
Good - AOP makes it possible to modularize these services and then apply them declaratively to the
components that they should affect. This results in components that are more cohesive and that focus on their
own specific concerns, completely ignorant of any system services that may be involved.

Spring

Enterprise applications often require certain services such as security and transactional support. One way of
applying these services is to code support for them directly into the classes that use them. For example, to
handle transactions, you may place the following snippet throughout your code:

    UserTransaction transaction = null;
    try {
        transaction = ... {retrieve transaction}
        transaction.begin();
        ... do stuff...
    transaction.commit();
    } catch (Exception e) {
        if (transaction != null) transaction.rollback();
    }

The problem with handling transactions this way is that you may repeat the same transaction handling code
several times—once for each time you need a transactional context. What’s more, your application code is
responsible for more than its core functionality.
EJB simplifies things by making it possible to declare these services and their policies in the EJB deployment
descriptor. With EJB it is possible to write components that are ignorant of the fact that they are in a
transactional context or being secured and then declare the transactional and security policies for those
components in the EJB deployment descriptor.

For example, to ensure that a method is transactional in EJB, you simply place the following in the deployment
descriptor:

<container-transaction>
    <method>
        <ejb-name>Foo</ejb-name>
        <method-intf>Remote</method-inf>
        <method-name>doSomething</method-name>
    </method>
    <trans-attribute>RequiresNew</trans-attribute>
</container-transaction>

EJB has hung its hat on how it simplifies infrastructure logic such as transactions and security. But EJB has
complicated matters in other ways.
Although Spring’s AOP support can be used to separate cross-cutting concerns from your application’s core
logic, its primary job is as the basis for Spring’s support for declarative transactions. Spring comes with several
aspects that make it possible to declare transaction policies for JavaBeans. And the Acegi Security System
(another open-source project associated with Spring) provides declarative security to JavaBeans. As with all
Spring configuration, the transactional and security policies are prescribed in a Spring configuration file.

For example, suppose your application handles student registration for training courses. Perhaps you have a
bean called StudentService-Impl that implements the following interface:

    public StudentService {
        public void registerForCourse(Student student, Course course);
    }

This bean may be registered in the Spring bean XML file as follows:

<bean id="studentServiceTarget" class="com.springinaction.training.StudentServiceImpl"/>


StudentService’s registerForCourse() method should perform the following actions:
    1 Verify that there is an available seat in the course.
    2 Add the student to the course’s roster.
    3 Decrement the course’s available seat count by 1.
    4 Notify the student by e-mail of a successful registration.

All of these actions should happen atomically. If anything goes bad, then all should be rolled back as if nothing
happened. Now imagine if you were to apply one of Spring’s transaction manager aspects. Applying
transactional support to StudentService-Impl might be as simple as adding the lines shown in listing bean XML
file.

<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory"/>
    </property>
</bean>

<bean id="studentService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="target">
        <ref bean="studentServiceTarget"/>
    </property>
    <property name="transactionAttributes">
    <props>
        <prop key="registerForCourse">
            PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT
        </prop>
    </props>
    </property>
    <property name="transactionManager">
            <ref bean="transactionManager"/>
    </property>
</bean>

Here we make use of Spring’s TransactionProxyFactoryBean. This is a convenience proxy class that allows us
to intercept method calls to an existing class and apply a transaction context. In this case we are creating a
proxy to our Student-ServiceImpl class and applying a transaction to the registerForCourse() method.

We are also using HibernateTransactionManager, the implementation of a transaction manager you would most
likely use if your application’s persistence layer is based on Hibernate.

Communication with Database in Spring

Step 1 – Add dataSource bean in hello.xml
    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://127.0.0.1:3306/test</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>root</value>
        </property>
    </bean>

Step 2 – Take the connection

    Resource res = new ClassPathResource("hello.xml");
    BeanFactory factory = new XmlBeanFactory(res);
    DataSource ds = (DataSource) factory.getBean("dataSource");
    Connection connection = ds.getConnection();
    //proceed….