In this Spring framework tutorial, we will learn how to write hello world
example. This should be the first tutorial to start learning Spring framework,
as it gets ball rolling and while coding and running this example, you learn a
lot about Spring framework, Spring XSD files, required JAR file and more
importantly how spring works.This Helloworld program in Spring framework is an
example of classical Java hello world program,
written using dependency Injection design pattern
by using Spring Framework's IOC container. Spring is so far one of the most
popular Java application framework, which promotes some best practices while
writing Java application e.g. dependency Injection. Spring provides an IOC
container to manage life-cycle of Spring beans and provides support to get beans
any time from IOC container. Apart from Spring's IOC container, it also provide
rich API to simply many of Java task e.g. JdbcTemplate help you
to write JDBC code without taking care of boiler plate things like closing
connection, statement, result-set etc. Similarly Spring framework also provides JmsTemplate to simply
JMS related task e.g. sending and receiving messages in Java. I first learned
about usefulness of Spring framework, while reading Expert Spring MVC and Web Flow,
it first few chapters, which explains about how dependency injection provides
improved testing, loose coupling and help in clean code. Those two chapters are
so far my best read on Spring, and I also suggest to take a look. By the way in
this Spring tutorial, we will see one of
the most simple example of Dependency Injection e.g. Hello Example. Message to
Hello class is provided by Spring framework using Dependency Injection.
Spring and Java HelloWorld Example
In this example we have created a bean or a Java class called Hello, which
accepts a String message as dependency. This spring bean
is initialized using spring configuration file i.e. spring-config.xml. All beans
declared in spring configuration file is created and managed by Spring IOC
container. If you look Spring configuration file, than you will find that id of
bean is "hello", which will be further used to
get reference of this bean from Spring framework using getBean() method of ApplicationContext or BeanFactory class. In order
to test this Spring HelloWorld example, we have created a Main class, which has
classical public static void main(String args[])
method. In main method, we are creating
an instance of ClassPathXMLApplicationContext by
providing spring-config.xml, which must be available in
classpath, in order for Spring to initialize beans. Next two lines of code is
self explanatory, where we are getting reference of Hello bean by
using "id" attribute of Hello bean declaration. For printing HelloWorld in console,
Instead of using System.out.println, we have used log4j. As its
important to setup logging in every Java application, I have configured log4j
using log4j.xml which is also available in classpath. By the way,
there are mainly two ways to inject dependency using Spring, Constructor injection and Setter
Injection, and this example uses setter injection to pass message to
Hello object.
So this Spring hello world example contains following configuration files
and Java classes.
Hello.java
- Hello Bean which prints message provided to it by using spring
dependency Injection
Main.java - Test class for this Spring
Helloworld example
spring-config.xml
- Spring configuration file which contains bean declaration
log4j.xml - log4j configuration file
Required
dependency JAR files
This Spring hello world example uses Spring 3.1.2.RELEASE.jar files e.g.
spring-core-3.1.2.RELEASE.jar
commons-logging-1.1.1.jar
log4j-1.2.16.jar
spring-context-3.1.2.RELEASE.jar
spring-aop-3.1.2.RELEASE.jar
aopalliance-1.0.jar
spring-beans-3.1.2.RELEASE.jar
In order to run this Spring hello world example, just run Main class as
Java application from command line or Eclipse IDE.
Spring
HelloWorld Java Class
import
org.apache.log4j.Logger;
/*
* Java class which accept message as
dependency injected
*/
public class Hello {
private static final Logger logger = Logger.getLogger(Hello.class);
private String message;
public void setMessage(String message)
{
this.message = message;
}
public String getMessage() {
return message;
}
public void sayHello(){
logger.info(“Hello world
Spring message is :” + message); }
}
Main
Class to Test HelloWorld Bean
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
/*
* Main class to start and test this Java
application
*/
public class Main {
public static void main(String args[]){
ApplicationContext
context = new ClassPathXmlApplicationContext(
"spring-config.xml");
Hello hello = (Hello) context.getBean("hello");
hello.sayHello();
}
}
log4j.xml
xml version="1.0" encoding="UTF-8"?>
DOCTYPE log4j:configuration SYSTEM
"log4j.dtd">
<log4j:configuration
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender" >
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-4r
[%t] %-5p %c %x - %m%n" />
layout>
appender>
<logger name="org.springframework" >
<level value="ERROR" />
<appender-ref ref="console" />
logger>
<logger name="org.apache">
<level value="DEBUG" />
<appender-ref ref="console" />
logger>
<root>
<level value="DEBUG" />
<appender-ref ref="console" />
root>
log4j:configuration>
Spring
Configuration File spring-config.xml
xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="hello" class="Hello">
<property name="message" value="Good
Afternoon" />
bean>
beans>
Output
Hello world Spring message is : Good Afternoon
Further Reading on Spring Framework
If you are beginner in
Spring and just started learning it, you may want to take a look at these books
to further learning on this popular Java framework
- Expert Spring
MVC - Spring
Recipes - Pro Spring 3
- Spring in
Action
That's all on this Spring and Java HelloWorld Example using dependency
Injection. For a Java programmer, knowledge of Spring framework is quickly
becoming from good to have, to must have and it's high time to learn and use
Spring framework while writing Java applications. Initially it take some time
to get used of XML and Spring configuration file, various spring releases and
JAR files and Spring API. Once you get hold of basics of Spring framework and dependency Injection design principle,
writing Java program in Spring framework is real fun.
Tidak ada komentar:
Posting Komentar