




















































In this article by Jérôme Jaglale, author of the book Spring Cookbook , we will cover the following recipes:
(For more resources related to this topic, see here.)
In this article, we will first cover the installation of some of the tools for Spring development:
Then, we will build a Springweb application and run it with Tomcat.
Finally, we'll see how Spring can also be used in a standard Java application (not a web application).
We will first install Java 8 because it's not installed by default on Mac OS 10.9 or higher version. Then, we will install Maven 3, a build tool similar to Ant, to manage the external Java libraries that we will use (Spring, Hibernate, and so on). Maven 3 also compiles source files and generates JAR and WAR files. We will also install Tomcat 8, a popular web server for Java web applications, which we will use throughout this book. JBoss, Jetty, GlassFish, or WebSphere could be used instead. Finally, we will install the Eclipse IDE, but you could also use NetBeans, IntelliJ IDEA, and so on.
Install Java first, then Maven, Tomcat, and Eclipse.
export JAVA_HOME="/Library/Java/JavaVirtualMachines/ jdk1.8.0_40.jdk/Contents/Home"
$ java -version
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
export MAVEN_HOME=~/bin/apache-maven-3.3.1
export PATH=$PATH:$MAVEN_HOME/bin
$ mvn –v
Apache Maven 3.3.1 (12a6b3...
Maven home: /Users/jerome/bin/apache-maven-3.3.1
Java version: 1.8.0_40, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_...
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.5", arch... …
chmod +x bin/*.sh
$ bin/catalina.sh run
Using CATALINA_BASE: /Users/jerome/bin/apache-tomcat-7.0.54
...
INFO: Server startup in 852 ms
./eclipse
Tomcat can be run as a background process using these two scripts:
bin/startup.sh
bin/shutdown.sh
On a development machine, it's convenient to put Tomcat's folder somewhere in the home directory (for example, ~/bin) so that its contents can be updated without root privileges.
We will first install Java 8. Then, we will install Maven 3, a build tool similar to Ant, to manage the external Java libraries that we will use (Spring, Hibernate, so on). Maven 3 also compiles source files and generates JAR and WAR files. We will also install Tomcat 8, a popular web server for Java web applications, which we will use throughout this book. JBoss, Jetty, GlassFish, or WebSphere could be used instead. Finally, we will install the EclipseIDE, but you could also use NetBeans, IntelliJ IDEA, and so on.
Install Java first, then Maven, Tomcat, and Eclipse.
sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
sudo apt-get install –y oracle-java8-installer
$ java -version
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)...
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25…
export MAVEN_HOME=~/bin/apache-maven-3.3.1
export PATH=$PATH:$MAVEN_HOME/bin
$ mvn –v
Apache Maven 3.3.1 (12a6b3...
Maven home: /home/jerome/bin/apache-maven-3.3.1
Java version: 1.8.0_40, vendor: Oracle Corporation
...
chmod +x bin/*.sh
$ bin/catalina.sh run Using CATALINA_BASE: /Users/jerome/bin/apache-tomcat-7.0.54 ... INFO: Server startup in 852 ms
./eclipse
Tomcat can be run as a background process using these two scripts:
bin/startup.sh bin/shutdown.sh
On a development machine, it's convenient to put Tomcat's folder somewhere in the home directory (for example, ~/bin) so that its contents can be updated without root privileges.
We will first install Java 8. Then, we will install Maven 3, a build tool similar to Ant, to manage the external Java libraries that we will use (Spring, Hibernate, and so on). Maven 3 also compiles source files and generates JAR and WAR files. We will also install Tomcat 8, a popular web server for Java web applications, which we will use throughout this book. JBoss, Jetty, GlassFish, or WebSphere could be used instead. Finally, we will install the Eclipse IDE, but you could also use NetBeans, IntelliJ IDEA, and so on.
Install Java first, then Maven, Tomcat, and Eclipse.
In this recipe, we will build a simple Spring web application with Eclipse. We will:
In the next recipe, we will compile and run this web application.
In this section, we will create a Spring web application in Eclipse.
Open Maven's pom.xml configuration file at the root of the project. Select the pom.xml tab to edit the XML source code directly. Under the project XML node, define the versions for Java and Spring. Also add the Servlet API, Spring Core, and Spring MVC dependencies:
<properties> <java.version>1.8</java.version> <spring.version>4.1.5.RELEASE</spring.version> </properties> <dependencies> <!-- Servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
package com.springcookbook.config; @Configuration @EnableWebMvc @ComponentScan (basePackages = {"com.springcookbook.controller"}) public class AppConfig { }
package com.springcookbook.config; public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[0]; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{AppConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
In the com.springcookbook.controller package, create the HelloController class and its hi() method:
@Controller public class HelloController { @RequestMapping("hi") @ResponseBody public String hi() { return "Hello, world."; } }
This section will give more you details of what happened at every step.
The generated Maven project is a pom.xml configuration file along with a hierarchy of empty directories:
pom.xml src |- main |- java |- resources |- webapp |- test |- java |- resources
The declared Maven libraries and their dependencies are automatically downloaded in the background by Eclipse. They are listed under Maven Dependencies in the left-hand side pane Package Explorer.
Tomcat provides the Servlet API dependency, but we still declared it because our code needs it to compile. Maven will not include it in the generated .war file because of the <scope>provided</scope> declaration.
AppConfig is a Spring configuration class. It is a standard Java class annotated with:
ServletInitializer is a configuration class for Spring's servlet; it replaces the standard web.xml file. It will be detected automatically by SpringServletContainerInitializer, which is automatically called by any Servlet 3. ServletInitializer extends the AbstractAnnotationConfigDispatcherServletInitializer abstract class and implements the required methods:
We created a controller class in the com.springcookbook.controller package, which we declared in AppConfig. When navigating to http://localhost:8080/hi, the hi()method will be called and Hello, world. will be displayed in the browser.
In this recipe, we will use the Spring web application from the previous recipe. We will compile it with Maven and run it with Tomcat.
Here are the steps to compile and run a Spring web application:
<build> <finalName>springwebapp</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.5</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
In pom.xml the boilerplate code prevents Maven from throwing an error because there's no web.xml file. A web.xml file was required in Java web applications; however, since Servlet specification 3.0 (implemented in Tomcat 7 and higher versions), it's not required anymore.
On Mac OS and Linux, you can create a symbolic link in Tomcat's webapps folder pointing to the.war file in your project folder. For example:
ln -s ~/eclipse_workspace/spring_webapp/target/springwebapp.war ~/bin/apache-tomcat/webapps/springwebapp.war
So, when the.war file is updated in your project folder, Tomcat will detect that it has been modified and will reload the application automatically.
In this recipe, we will build a standard Java application (not a web application) using Spring. We will:
In this section, we will cover the steps to use Spring in a standard (not web) Java application.
Open Maven's pom.xml configuration file at the root of the project. Select the pom.xml tab to edit the XML source code directly. Under the project XML node, define the Java and Spring versions and add the Spring Core dependency:
<properties> <java.version>1.8</java.version> <spring.version>4.1.5.RELEASE</spring.version> </properties> <dependencies> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
@Configuration public class AppConfig { }
Create a User Java class with two String fields:
public class User { private String name; private String skill; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } }
In the AppConfig class, define a User bean:
@Bean public User admin(){ User u = new User(); u.setName("Merlin"); u.setSkill("Magic"); return u; }
package com.springcookbook.main; public class Main { public static void main(String[] args) { } }
AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class); User admin = (User) springContext.getBean("admin"); System.out.println("admin name: " + admin.getName()); System.out.println("admin skill: " + admin.getSkill()); springContext.close();
We created a Java project to which we added Spring. We defined a User bean called admin (the bean name is by default the bean method name).
In the Main class, we created a Spring context object from the AppConfig class and retrieved the admin bean from it. We used the bean and finally, closed the Spring context.
In this article, we have learned how to install some of the tools for Spring development. Then, we learned how to build a Springweb application and run it with Tomcat. Finally, we saw how Spring can also be used in a standard Java application.