Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts

Friday, November 9, 2012

Step by step Spring Hello World Tutorial


Here it is.. the simple step by step "Hello World" tutorial using the Spring Framework. Here I used Spring's dependency injection concept to inject the value into an object.

We are going to create a new project in Eclipse Java EE IDE and then write a simple Hello World application. We will finally run the application in the Eclipse IDE.

Just jump to Step 3 directly if you already hava JDK 5 (or higher) and Eclipse IDE.

Tools Used:

1) Jdk 5 or Higher.
2) Eclipse 3
3) Spring 3.2.0.RELEASED

Step 1:
Download Java JDK :The first step of Developing an application using Java Programming Language, you need JDK(Java Development Kit). The Spring 3.X at least requires JDK 5. So, make sure you have JDK 5 or above. Open dos prompt if you are using windows and type "java -version". This will display the version of Java installed on your machine as shown below:

C:\>java -version
java version "1.6.0_17"
Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
Java HotSpot(TM) Client VM (build 14.3-b01, mixed mode, sharing)

Make sure the java version is "1.5.x.x" or Higher
If you don't have Java JDK yet then download it through :
http://www.oracle.com/technetwork/java/javase/downloads/index.html

Step 2:
Download “Eclipse IDE for Java EE Developers” from Eclipse official website at http://www.eclipse.org/downloads/
The Current version of Eclipse IDE is Eclipse Juno (4.2)

Installing Eclipse IDE is easy task, just extract the downloaded file and you will find the eclipse.exe in the extracted folder. To run the IDE, double click on the eclipse.exe file.

Step 3:
Download the latest version of Spring 3 from 
http://www.springsource.org/download

For this tutorial we have downloaded spring-framework-3.1.1.RELEASE-with-docs.zip,which contains the documentation and all the required JAR files. the current Release of Spring Framework is 3.1.3.RELEASE.  After downloading just extract the folder you will get the structure like below. We will use these resource later in this tutorial.


Let's start developing "Hello World" example code:

1) I am going to start with a black workspace. Right click in your project Explorer -> New -> Java Project.

2) a 'New Java Project' window will be appear. In the "Project Name" field type the name of your project. then click "Finish".

3) Expand your project you will get a blank 'src' folder along with some detauls JAR files.


4) Our next task is to add all the JAR files into our project build path. For doing this  - right click on your project folder, select 'Build Path'  then select 'Configure Build Path.."

5) Now under the "Libraries" tab select "Add External JARs".


6) Navigate to all the JAR files under the 'dist' folder which we have been downloaded earlier (in Step 3).


7) Along with these JARs, we need to add an another JAR file named "commons-logging-1.1.1.jar"  (version might be different at the time you will download it). just download this JAR file  from here..
http://commons.apache.org/logging/download_logging.cgi
I have been already download this so i am going to navigate this file to our project's build path.


8) You will get a new label "Referenced Libraries" containing our all the external JARs.



9)  Now our next task is to add a package in our blank 'src' folder. Right click on it -> New -> package.


10) Under the name field type the name of your package. for this tutorial type "org.sumit.com.tutorials" then click Finish.


11) Now right click on package -> New -> Class. Under the name field type "MainApp". check mark on 'public static void main' option then Finish.
Repeat #11 (except don't check on 'public static void main' option) and add an another class named "HelloWorld".


# Code for MainApp.java


package org.sumit.com.tutorials;

/**
* @author SUMIT SAM
*
*/

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

@SuppressWarnings("deprecation")
public class MainApp {

public static void main(String[] args){

BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("Spring.xml"));
HelloWorld helloWorld = (HelloWorld)beanFactory.getBean("helloWorld");
helloWorld.show();
}
}

#Code for HelloWorld.java
package org.sumit.com.tutorials;
/**
* @author SUMIT SAM
*
*/
public class HelloWorld {
private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public void show(){
System.out.println(getMessage() +" By Java Help Centre");
}
}

12) Here we need our Spring Configuration file or Bean file. which inject values to the objects. For this tutorials I used an XML file.  Right click on your project folder -> New -> other -> XML file. click on Next.



13) type the name of your spring configuration file. name is user defined(can be anything).



#Code for spring.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="helloWorld" class="org.sumit.com.tutorials.HelloWorld" >
<property name="message" value="Hello World"/>
</bean>
</beans>

14)  Ultimately the final structure of your project would be looks like this. All done :) Just run your project for doing this right click on your project folder -> Run as -> Java Application.

If everything has done right. You will get result "Hello World By Java Help Centre" as output in console like below.
Image

Thank you for going through this tutorial. and Please let me know if you get any problem in this tutorial.

-
JHC Admin

Friday, October 5, 2012

Annotation based configuration in Spring

Now It is possible to configure Spring's dependency injection with annotations. This means that annotations can be used in Spring to mark fields, methods and classes that need dependency injection. Spring also supports auto-wiring of the bean dependencies, that is, resolving the collaborating beans by inspecting the contents of the BeanFactory.

Now there are annotations that can be used to indicate fields that are to be auto-wired. Furthermore, auto-detection of annotated components in the classpath is also supported now. When these capabilities are combined, the amount of configuration and dependency mapping in the Spring configuration files is reduced drastically.

According to the Spring development team, the core theme of Spring 2.5 that was released in October 2007 is to provide comprehensive support for configuration annotations in application components. Annotation support was first announced in Spring 2.0, and has been significantly enhanced in Spring 2.5. It introduces support for a complete set of configuration annotations.

I'll briefly discuss the annotation-driven configuration and auto-detection support in Spring 2.5 with the help of a simple tutorial.

What you need before you start
You need the following software to try out the tutorial.

Java 5.0
Spring Framework 2.5
You also need the following jars in your classpath. These are available with the Spring distribution.

  • spring.jar

  • asm-2.2.3.jar

  • asm-commons-2.2.3.jar

  • aspectjweaver.jar

  • aspectjrt.jar

  • hsqldb.jar

  • commons-logging.jar

  • log4j-1.2.14.jar

  • junit-4.4.jar

  • spring-test.jar

  • common-annotations.jar(This is not required if Java 6.0 or later is used)

Adding the classes and interfaces for the example

The example is just a simple service that returns a different message when an employee is hired or fired.

Let me start with the EmployeeService interface.


package emptest;
public interface EmployeeService {
 String hire(String name);
        String fire(String name);
}

package emptest; public interface EmployeeService { String hire(String name); String fire(String name); }


Here is a simple class that implements this interface.

@Service
public class EmployeeServiceImpl implements EmployeeService {
 @Autowired
 private EmployeeDao employeeDao;

 public String hire(String name) {
  String message = employeeDao.getMessage("Hire");
  return name + ", " + message;
 }

 public String fire(String name) {
  String message = employeeDao.getMessage("Fire");
  return name + ", " + message;
 }

 public void setEmployeeDao(EmployeeDao employeeDao) {
  this.employeeDao = employeeDao;
 }
}


Stereotype Annotations

Classes marked with stereotype annotations are candidates for auto-detection by Spring when using annotation-based configuration and classpath scanning. The  Component annotation is the main stereotype that indicates that an annotated class is a "component". The @Service stereotype annotation used to decorate the EmployeeServiceImpl class is a specialized form of the @Component annotation. It is appropriate to annotate the service-layer classes with @Service to facilitate processing by tools or anticipating any future service-specific capabilities that may be added to this annotation. The @Repository annotation is yet another stereotype that was introduced in Spring 2.0 itself.

This annotation is used to indicate that a class functions as a repository (the EmployeeDAOImpl below demonstrates the use) and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring's DataAccessException hierarchy, even when using plain JPA in the DAO classes.

@autowired

Another annotation used in EmployeeServiceImpl is @autowired . This is used to autowire the dependency of the EmployeeServiceImpl on the EmployeeDao . Here is the EmployeeDao interface.

public interface EmployeeDao {
    String getMessage(String messageKey);
}


The implementing class EmployeeDaoImpl uses the @Repository annotation.

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

 private SimpleJdbcTemplate jdbcTemplate;

 public String getMessage(String messageKey) {
  return jdbcTemplate.queryForObject(
    "select message from messages where messagekey = ?",
    String.class, messageKey);
 }

 @Autowired
 public void createTemplate(DataSource dataSource) {
  this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
 }
}


Here again, the DataSource implementation is autowired to the argument taken by the method that creates the SimpleJdbcTemplate object.

Simplified Configuration

The components discovered by classpath scanning are turned into Spring bean definitions, not requiring explicit configuration for each such bean. So the Spring configuration xml file is very simple.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd           http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd           http://www.springframework.org/schema/context           
" title="http://www.springframework.org/schema/context/spring-context-2.5.xsd">
">http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config />
 <context:component-scan base-package="emptest" />
 <aop:aspectj-autoproxy />

 <context:property-placeholder location="classpath:jdbc.properties" />

 <bean id="dmdataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${jdbc.driver}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
 </bean>

</beans>


Now let me explain the new configurations in the above Spring context file. The element is used to automatically register all of Spring's standard post-processors for annotation-based configuration. The annotation> element is used to enable autodetection of the stereotyped classes in the package emptest . Since the  AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are both included implicitly when using the component-scan element, the

element can be omitted. The properties for the data source are taken from the jdbc.properties file in the classpath. The property placeholders are configured with the element.

The element is used to enable @AspectJ support in Spring.

@Aspect

The @Aspect annotation on a class marks it as an aspect along with @Pointcut definitions and

advice (@Before, @After, @Around) as demonstrated in the TraceLogger class defintion below. The

PointCut is applied for all methods in the EmployeeServiceImpl class. The @Before annotation

indicates that the log() method in the TraceLogger is to be invoked by Spring AOP prior to

calling any method in EmployeeServiceImpl.

@Component
@Aspect
public class TraceLogger {
 private static final Logger LOG = Logger.getLogger(TraceLogger.class);

 @Pointcut("execution(* emptest.EmployeeServiceImpl.*(..))")
 public void empTrace() {
 }

 @Before("empTrace()")
 public void log(JoinPoint joinPoint) {
  LOG.info("Before calling " + joinPoint.getSignature().getName()
    + " with argument " + joinPoint.getArgs()[0]);
 }

}


Since there is no definition provided for TraceLogger in the Spring context file, it is marked for auto-detection from the classpath using the @Component annotation.


@Qualifier and @Resource


Suppose there is one more DataSource configuration in the spring context file as follows.

<bean id="jndidataSource"
 class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="jdbc/test" />
</bean>


Since auto-detection is enabled, auto-wiring will fail since both data source beans are equally eligible candidates for wiring. It is possible to achieve by-name auto-wiring by providing a bean name within the @Qualifier annotation as follows. The below method injects the DataSource implementation by specifying the name “dmdataSource”.

@Autowired
public void createTemplate(@Qualifier("dmdataSource") DataSource dataSource) {
  this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}



JSR-250 Annotations


Spring also provides support for Java EE 5 Common Annotations (JSR-250). The supported annotations are @Resource, @PostConstruct and @PreDestroy. The @Resource annotation is also supported by Spring for autowiring as shown in the below code, the bean name to be autowired is passed.

@Resource(name = "dmdataSource")
public void createTemplate(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}


The JSR-250 lifecycle annotations @PostConstruct and @PreDestroy can be used to specify initialization callbacks and destruction callbacks respectively. To demonstrate the use of these, I am adding the following code to the EmployeeDaoImpl class.

@PostConstruct
public void initialize() {
 jdbcTemplate.update("create table messages (messagekey varchar(20), message 

varchar(100))");
 jdbcTemplate.update("insert into messages (messagekey, message) values ('Hire', Congrats! 

You are hired')");
 jdbcTemplate.update("insert into messages (messagekey, message) values ('Fire', 'Sorry! 

You are fired')");
}

@PreDestroy
public void remove() {
 jdbcTemplate.update("drop table messages");
}



Unit Testing


Before testing the service implementation, I provided the database configuration details in the jdbc.properties file as follows.
jdbc.driver=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:blog
jdbc.username=sa
jdbc.password=

Here is the class I wrote for unit testing.

public class EmployeeServiceImplTests extends
  AbstractDependencyInjectionSpringContextTests {
 @Autowired
 private EmployeeService employeeService;

 @Override
 protected String[] getConfigLocations() {
  return new String[] { "context.xml" };
 }

 public void testHire() {
  String name = "Tom";
  String message = employeeService.hire(name);
  assertEquals(name + ", " + "Congrats! You are hired", message);
 }

 public void testGermanWelcome() {
  String name = "Jim";
  String message = employeeService.fire(name);
  assertEquals(name + ", " + "Sorry! You are fired", message);
 }

 public void setEmployeeService(EmployeeService employeeService) {
  this.employeeService = employeeService;
 }
}



Resources


You can download the source code for this tutorial

href="http://weblogs.java.net/blog/seemarich/archive/springannotations/SpringAnnotationsTestApp.z

ip">here.

The inputs from the following sources were very helpful in writing this tutorial.

Rod Johnson's

article on Spring 2.5

Spring 2.5

Documentation


Summary


I hope this discussion has opened up the possibilities offered by the annotation-based configuration capabilities in Spring 2.5. The tutorial does not include the annotations such as @Transactional, @Required and @PersistenceContext / @PersistenceUnit. These were introduced as earlier as Spring 2.0 itself.

The @Transactional annotation can be used to configure transactional setting for the public methods of a class or interface. The transactional behavior of the class annotated with @Transactional can be easily enabled with the element in the xml configuration file.

The @Required annotation is used to specify that the value of a bean property is required to be dependency injected. That means, an error is caused if a value is not specified for that property.

JPA integration is supported by Spring with the @PersistenceContext and @PersistenceUnit annotations for injecting the EntityManager and EntityManagerFactory respectively.