You’ll learn: • How to develop with the core Spring Framework, aspect oriented programming, dependency injection, and inversion of control • How to create Spring web services using Sprin
Trang 1Deinum Rubio
Long Mak
US $49.99Shelve inProgramming Languages/Java
User level:
Intermediate
SOURCE CODE ONLINE
Spring Recipes
Spring Recipes: A Problem-Solution Approach, Third Edition builds upon the best-selling
success of the previous editions and focuses on the latest Spring Framework features for building enterprise Java applications This book provides code recipes for the following, found
in the latest Spring:
• Spring fundamentals: Spring IoC container, Spring AOP/ AspectJ, and more
• Spring enterprise: Spring Java EE integration, Spring Integration, Spring Batch, Spring Remoting, messaging, transactions, and working with big data and the cloud using
Hadoop and MongoDB
• Spring web: Spring MVC, other dynamic scripting, integration with the popular Grails Framework (and Groovy), REST/web services, and more
This book guides you step-by-step through topics using complete and real-world code examples
When you start a new project, you can consider copying the code and configuration files from this book, and then modifying them for your needs This can save you a great deal of work over
creating a project from scratch!
You’ll learn:
• How to develop with the core Spring Framework, aspect oriented programming, dependency injection, and inversion of control
• How to create Spring web services using Spring REST, SOAP and remoting
• How to build a web client using Spring MVC and how to work with other web frameworks
• How to use Grails and Groovy
• How to integrate Spring with social media and mobile apps
• How to work with Spring Data, Batch, NoSQL and big data; then integrating with Hadoop, MongoDB, Redis and more
• How to create and manage Spring transactions
• How to handle Spring messaging, integration, testing, and caching
• How to secure your Spring applications
THIRD EDITION
RELATED
9 781430 259084
5 4 9 9 9 ISBN 978-1-4302-5908-4
Co vers
Spring
Framew ork 4.0
Trang 2For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them
Trang 3Contents at a Glance
About the Authors ���������������������������������������������������������������������������������������������������������� xxxiii
About the Technical Reviewer ���������������������������������������������������������������������������������������� xxxv
Trang 4Chapter 16: Spring Integration
Trang 5The Spring framework is growing It has always been about choice Java EE focused on a few technologies, largely to the detriment of alternative, better solutions When the Spring framework debuted, few would have agreed that Java EE represented the best-in-breed architectures of the day Spring debuted to great fanfare, because it sought to simplify Java
EE Each release since marks the introduction of new features designed to both simplify and enable solutions
With version 2.0 and later, the Spring framework started targeting multiple platforms The framework provided services on top of existing platforms, as always, but was decoupled from the underlying platform wherever possible Java EE is a still a major reference point, but it’s not the only target Additionally, the Spring framework runs on different Cloud environments With the introduction of Java based configuration and more XML schemas, the Spring framework created powerful configuration options Frameworks built on top of the Spring framework have emerged supporting application integration, batch processing, messaging, and much more
This is the 3rd edition of the superb Spring Recipes and it contains mostly updated frameworks, describing the new features and explaining the different configuration (Java and/or XML) options Additionally, new projects have been added to the Spring ecosystem like the Spring Data family of products
It was impossible to describe each and every project in the Spring ecosystem, so we had to decide what to keep, what to add, and what to update This was a hard decision but we think we have included the most important and used content.Who This Book Is For
This book is for Java developers who want to simplify their architecture and solve problems outside the scope of the Java
EE platform If you are already using Spring in your projects, the more advanced chapters present discussions of newer technologies that you might not know about already If you are new to the framework, this book will get you started in no time This book assumes that you have some familiarity with Java and an IDE of some sort While it is possible, and indeed useful, to use Java exclusively with client applications, Java’s largest community lives in the enterprise space and that, too, is where you’ll see most of these technologies deliver the most benefit Thus, some familiarity with basic enterprise programming concepts like the Servlet API is assumed
How This Book Is Structured
Chapter 1, “Spring Development Tools”, gives an overview of tools supporting the Spring framework and how to use them.Chapter 2, “Spring core tasks,” gives a general overview of the Spring framework: how to set it up, what it is, and how it’s used
Chapter 3, “Spring Annotation Driven Core Task,” reviews, in addition to Chapter 2 more annotation driven concepts that are still key to fully exploiting the container
Chapter 4, “Spring @MVC,” covers web-based application development using the Spring Web MVC framework Chapter 5, “Spring REST,” provides an introduction to Spring’s support for RESTful web services
Chapter 6, “Spring Social,” provides an introduction of Spring Social, which lets you integrate easily with social networks Chapter 7, “Spring Security,” provides an overview of the Spring Security project, to help you better secure your application
Chapter 8, “Spring Mobile,” provides an introduction of Spring Mobile, which lets you integrate Mobile device detection and usage in your application
Trang 6Chapter 9, “Integrating Spring with Other Web Frameworks,” introduces the core web-tier support that Spring provides This provides a base for all technologies that Spring provides in the web tier
Chapter 10, “Data Access,” discusses using Spring to talk to data stores using APIs like JDBC, Hibernate, and JPA Chapter 11, “Transaction Management in Spring,” introduces the concepts behind Spring’s robust transaction management facilities
Chapter 12, “Spring Batch,” introduces the Spring Batch framework, which provides a way to model solutions traditionally considered the domain of mainframes
Chapter 13, “NoSQL and BigData,” an introduction to multiple Spring Data portfolio projects, covering different NoSQL technologies and BigData with Hadoop
Chapter 14, “Spring Java Enterprise Services and Remoting Technologies,” introduces you to the JMX support, scheduling, e-mail support, and various facilities for RPC, including the Spring Web Services project
Chapter 15, “Spring Messaging,” discusses using Spring with message-oriented middleware through JMS and RabbitMQ and the simplifying Spring abstractions
Chapter 16, “Spring Integration,” discusses using the Spring Integration framework to integrate disparate services and data
Chapter 17, “Spring Testing,” discusses unit testing with the Spring framework
Chapter 18, “Grails,” discusses the Grails framework, with which you can increase your productivity by using of-breed pieces and gluing them together with Groovy code
best-Appendix A, “Deployment to the Cloud,” shows how to deploy a Java (Web) application to the cloud using the Pivotals CloudFoundry solution
Appendix B, “Spring Caching,” introduces the Spring Caching abstraction, including how to configure it and how
to transparently add caching to your application
Because the Java programming language is platform independent, you are free to choose any supported operating system However, some of the examples in this book use platform-specific paths Translate them as necessary to your operating system’s format before typing the examples
To make the most of this book, install JDK version 1.7 or higher You should have a Java IDE installed to make
development easier For this book, the sample code is Gradle based If you’re running Eclipse and Install the Gradle plug-in, you can open the same code in Eclipse and the CLASSPATH and dependencies will be filled in the by the Gradle metadata
If you’re using Eclipse, you might prefer SpringSource’s SpringSource Tool Suite (STS), as it comes preloaded with the plug-ins you’ll need to be productive with the Spring framework in Eclipse If you use IntelliJ IDEA, you need to enable the Gradle (and Groovy) plugins
Downloading the code
The source code for this book is available from the Apress web site (www.apress.com) in the Source Code / Download section The source code is organized by chapters, each of which includes one or more independent examples Contacting the Authors
We always welcome your questions and feedback regarding the contents of this book You can contact Marten Deinum
at marten@deinum.biz
Trang 7Spring Development Tools
In this chapter you’ll learn how to setup and work with the most popular development tools to create Spring
applications Like many other software frameworks, Spring has a wide array of development tools to choose from, from bare-bones command line tools to sophisticated graphical tools the software industry calls IDEs (Integrated Development Environments)
Whether you already use certain Java development tools or are a first-time developer, the following recipes will guide you on how to set up different toolboxes to do the exercises in the upcoming chapters, as well as develop any Spring application
Table 1-1 describes a list of toolboxes and the corresponding recipes you need to follow to get the right tools to start a Spring application
Table 1-1 Toolboxes to develop Spring applications
Toolbox A Toolbox B Toolbox C Toolbox D
Spring Tool Suite
Recipe 1-1
Eclipse IDERecipe 1-2
IntelliJ IDERecipe 1-3w/Maven CLI Recipe 1-4
Text editorw/Maven CLI Recipe 1-4w/Gradle CLI Recipe 1-5 w/Gradle CLI Recipe 1-5
Bear in mind you don’t need to install every toolbox described in Table 1-1 to work with Spring It can be helpful
to try them all out, so you can use the toolbox you feel most comfortable with
1-1 Build a Spring application with the Spring Tool Suite
‘Existing Maven projects’ Next, select the Spring application based on Maven from your workstation
Trang 8To install Gradle on STS, click on the ‘Extensions’ tab at the bottom of the dashboard window Click on the
‘Gradle Support’ checkbox Proceed with the Gradle extension installation and restart STS once the installation is complete To open a Spring application that uses Gradle, from the top level ‘File’ menu select the ‘Import ’ option, click on the ‘Gradle’ icon and select the ‘Gradle project’ Next, select the Spring application based on Gradle from your workstation Click on the ‘Build Model’ button and last click ‘Finish’ to start working on the project
How It Works
STS is the IDE developed by SpringSource a division of Pivotal creators of the Spring framework STS is
specifically designed to develop Spring applications, making it one of the most complete tools for this purpose STS is
an Eclipse-powered tool, so it has the same ‘look and feel’ as the Eclipse open source IDE
STS can be downloaded for free from http://spring.io/tools/sts STS is available for all six major operating system (OS) versions: Windows, Windows (64bit), Mac OS X (Cocoa), Mac OS X (Cocoa, 64bit), Linux (GTK), and Linux (GTK, 64bit) STS is also distributed in two versions of Eclipse, the Eclipse 3.x branch and the Eclipse 4.x branch In addition, STS is itself versioned, so you have the option to download the latest stable release or a milestone/development version
Download the version suited to your OS and I recommend you chose the Eclipse 4.x branch because it’s newer
At the time of this writing the latest stable release of the Spring Tool Suite is the 3.5 version Therefore the download link you chose should have the title ‘SPRING TOOL SUITE 3.5.1.RELEASE - BASED ON ECLIPSE 4.3.2’ or you can choose a newer release if you prefer
Once you download STS, ensure you have a Java SDK installed on your system since this is an STS installation requirement Proceed to install STS Follow the installation wizard and you should have STS setup in 5 to 10 minutes Upon termination, a folder with the name STS_<VERSION> is created under the home folder of the user making the installation or where the user chooses to place the installation-based folder If you inspect this folder, you’ll see the STS executable which is used to start STS
Start STS At startup, STS asks you to define a workspace location A workspace is where STS places all project information You can keep the default directory which is under the main STS installation directory or define a different directory to your liking After startup is complete you’ll see a screen like the one in Figure 1-1
Figure 1-1 STS startup screen
Trang 9Click on the ‘Open Dashboard’ link Then you’ll see the STS Dashboard illustrated in Figure 1-2.
Figure 1-2 STS Dashboard
On the STS Dashboard, in the center column inside the ‘Create’ box there’s a link called ‘Spring project’ You can click on this link to create a new Spring application You can go ahead and create an empty application if you like You’ll be asked for a name and to define a series of parameters which you can leave with default values
A more common case than creating a Spring application from scratch is to continue development on a
pre-existing Spring application Under such circumstances, the owner of an application generally distributes the application’s source code with a build script to facilitate its ongoing development
The build script of choice for most Java application is a pom.xml file designed around the build tool called Maven and more recently a build.gradle file designed around the build tool called Gradle The book’s source code and its applications are provided with Gradle build files, in addition to a single application with a Maven build file
JaVa BUILD tOOLS, a MeaNS tO aN eND: aNt, MaVeN, IVY, GraDLe
in a Java application there can be dozens or hundreds of menial tasks required to put together an application (e.g., Copying Jars or configuration files, setting up Java’s classpath to perform compilation, downloading Jar dependencies, etc.) Java build tools emerged to perform such tasks in Java applications.
Java build tools continue to have their place because applications distributed with build files ensure that all
menial tasks intended by the creator of an application are replicated exactly by anyone else using the application
if an application is distributed with an ant build.xml file, a maven pom.xml file, an ivy ivy.xml file or a gradle build gradle file, each of these build files guarantees build consistency across users and different systems.
Trang 10Some of the newer Java build tools are more powerful and enhance the way their earlier counterparts work and each build file uses its own syntax to define actions, dependencies, and practically any other task required to build an application however, you should never lose sight of the fact that a Java build tool is just a means to an end it’s a choice made by the creator of an application to streamline the build process.
Don’t panic if you see an application distributed with a build file from the oldest ant version or the newest gradle version, from an end user perspective all you need to do is download and install the build tool to create the
application as its creator intended.
Since many Spring applications continue to use Maven and some of the newer Spring applications use Gradle, I’ll describe the import process into STS for both types of projects
Once you download the book’s source and unpack it to a local directory, click on the STS top level ‘File’ menu and select the ‘Import ’ option A pop-up window appears In the pop-up window, click on the ‘Maven’ icon and select the ‘Existing Maven Projects’ option as illustrated in Figure 1-3
Figure 1-3 STS maven import
Trang 11Notice in Figure 1-4 the ‘Projects:’ window is updated to include the line pom.xml com.apress.
springrecipes which reflects the Maven project to import Select the project checkbox and click on the ‘Finish’ button to import the project All projects in STS are accessible on the left-hand side in the ‘Package Explorer’ window
In this case, the project appears with the name springintro_mvn
If you click on the project icon in the ‘Package Explorer’ window, you’ll be able to see the project structure (i.e., java classes, dependencies, configuration files, etc.) If you double click on any of the project files inside the
‘Package Explorer’, the file is opened in a separate tab in the center window alongside the dashboard Once a file is opened, you can inspect, edit, or delete its contents
Select the project icon in the ‘Package Explorer’ window and click on the right button of your mouse
A contextual menu appears with various project commands Select the ‘Run as’ option followed by the ‘Maven build’ option A pop-up window appears to edit and configure the project build Just click on the ‘Run’ button in the bottom right In the bottom center of STS you’ll see the ‘Console’ window appear In this case, the ‘Console’ window displays a series of build messages produced by maven, as well as any possible errors in case the build process fails
Next, click on the ‘Next’ button In the following screen, on the ‘Select root directory’ line click on the ‘Browse’ button and select the directory of the book’s source code in Ch1 called springintro_mvn as illustrated in the Figure 1-4
Figure 1-4 STS select maven project
Trang 12You’ve just built the application, congratulations! Now let’s run it Select the project icon from the ‘Package Explorer’ window once again and press the F5 key to refresh the project directory Expand the project tree Toward the bottom you’ll see a new directory called target which contains the built application Expand the target directory by clicking on its icon Next, select the file springintro_mvn-1.0-SNAPSHOT.jar as illustrated in Figure 1-5
Figure 1-5 Select executable in STS
Trang 13Click on the ‘Run’ button in the bottom right In the bottom center of STS you’ll see the ‘Console’ window In this case, the ‘Console’ window displays the application logging messages, as well as a greeting message defined by the application.Even though you’ve built and run a Spring application with STS, we’re still not done The process you just completed with STS was mostly done behind the scenes by the build tool called Maven Next, it’s time to import a Spring application that uses one of the newer build tools call Gradle.
While gradle is still a relatively new tool, there are signs that gradle will supplant Maven in the future For example, many large Java projects such as the Spring framework itself now use Gradle instead of maven due to its greater simplicity and power Given this tendency, it’s a worth describing how to use Gradle with STS
Figure 1-6 Define main executable class in STS
With the file selected, click on the right button of your mouse A contextual menu appears with various project commands Select the ‘Run as’ option followed by the ‘Run configurations ’ option A pop-up window to edit and configure the run appears Ensure the ‘Java application’ option is selected on the left-hand side In the ‘Main class:’ box introduce: com.apress.springrecipes.hello.Main This is the main class for this project, as illustrated in Figure 1-6
Trang 14To install Gradle in STS go to the dashboard window At the bottom of the dashboard window click on the
‘Extensions’ tab A list of STS extensions is loaded in the window Click on the ‘Gradle Support’ checkbox from the list as illustrated in Figure 1-7 If you don’t see the ‘Gradle Support’ extension in the list, type the word ‘gradle’ in the
‘Find:’ textbox If you still don’t see the ‘Gradle Support’ extension after this step, click on the ‘Find Updates’ button
Figure 1-7 Gradle STS installation
Trang 15Click on the ‘Next’ button in the bottom right to proceed with the Gradle extension installation A confirmation pop-up window appears as illustrated in Figure 1-8
Figure 1-8 Gradle STS installation confirmation
Click on the pop-up window’s ‘Next’ button Once you read the license and accept the terms click on the
pop-up window’s ‘Finish’ button The Gradle extension installation process starts Once the installation process finishes, you’ll be prompted to restart STS for the changes to take effect Confirm the STS restart to finish the Gradle installation
Trang 16The book’s source contains numerous Spring applications designed to be built with Gradle, so I’ll describe how
to import these Spring applications into STS Once you download the book’s source and unpack it to a local directory,
in STS click on the top level ‘File’ menu and select the ‘Import ’ option A pop-up window appears In the pop-up window, click on the ‘Gradle’ icon and select the ‘Gradle Project’ option as illustrated in Figure 1-9
Figure 1-9 STS gradle import
Next, click on the ‘Next’ button In the following screen, in the ‘Select root directory’ line click on the ‘Browse’ button and select the book’s source code top level directory Next, click on the ‘Build model’ button beside the
‘Browse’ button The build model process retrieves the various Gradle subprojects contained in the book’s source code A pop-up window appears indicating the progress of the build model process Once the build model process finishes, you’ll see a list of Gradle projects, click on the project checkbox called ‘springintro’ inside ‘Ch1’ as illustrated
in Figure 1-10
Trang 17Click on the ‘Finish’ button to import the project If you look at the left-hand side of STS in the ‘Package Explorer’ window you’ll see the project is loaded with the name springintro If you click on the project icon, you’ll be able to see the project structure (i.e., java classes, dependencies, configuration files, etc.).
Select the project icon and click on the right button of your mouse A contextual menu appears with various project commands Select the ‘Run as’ option followed by the ‘Gradle build’ option A pop-up window appears to edit and configure the build Click on the Project/task option ‘build’ and then click on the ‘Run’ button in the bottom right In the bottom center of STS you’ll see the ‘Console’ window appear In this case, the ‘Console’ window displays a series of build messages produced by gradle, as well as any possible errors in case the build process fails
You’ve just built the application, now let’s run it Select the project icon once again and press the F5 key to refresh the project directory Expand the project tree Toward the middle you’ll see a new directory called libs which contains the built application Expand the libs directory by clicking on the icon Next, select the file springintro-1.0-SNAPSHOT.jar
Figure 1-10 STS select gradle subproject
Trang 18With the file selected, from the top level menu ‘Run’ select the ‘Run configurations ’ option A pop-up window appears to edit and configure the run Ensure the ‘Java application’ option is selected in the left-hand side In the
‘Main class:’ box introduce com.apress.springrecipes.hello.Main This is the main class for this project Click on the ‘Run’ button in the bottom right In the bottom center of STS you’ll see the ‘Console’ window In this case, the
‘Console’ window displays the application logging messages, as well as a greeting message defined by the application
1-2 Build a Spring application with the Eclipse IDE
‘Spring project’ option
To open a Spring application that uses Maven, you first need to install Maven Integration for Eclipse
(a.k.a m2eclipse) From Eclipse’s top level ‘Help’ menu select the ‘Eclipse Marketplace ’ Install Maven Integration for Eclipse Click on the Eclipse top level ‘File’ menu and select the ‘Import ’ option A pop-up window appears
In the pop-up window, click on the ‘Maven’ icon and select the ‘Existing Maven Projects’ option Next, seledct the Spring application based on Maven from your workstation
To open a Spring application that uses Gradle, you first need to install Gradle Integration for Eclipse From Eclipse’s top level ‘Help’ menu select the ‘Eclipse Marketplace ’ Install Maven Integration for Eclipse Click on the Eclipse top level ‘File’ menu and select the ‘Import ’ option A pop-up window appears In the pop-up window, click
on the ‘Gradle’ icon and select the ‘Gradle Project’ option Next, select the Spring application based on Gradle from your workstation
Eclipse supports a wide variety of tools that make it easy to work with certain technologies directly in the Eclipse IDE Some of these tools include support for version control technologies like svn and git, support for platform technologies like Python and Android and as you probably already guessed support for the Spring framework Eclipse makes all these tools available in what it calls the Eclipse marketplace
Trang 19■ if you don’t see the ‘eclipse marketplace ’ option illustrated in Figure 1-11 it means your eclipse version doesn’t support the eclipse marketplace the eclipse marketplace is included in all eclipse packages available from the eclipse download page, except the eclipse classic package.
Once you select the ‘Eclipse Marketplace ’ option a pop-up window appears where you can access and search the Eclipse marketplace
Figure 1-11 Eclipse Marketplace option
You can access the Eclipse marketplace at its website (http://marketplace.eclipse.org/) or directly in the Eclipse IDE from the top level ‘Help’ menu selecting the ‘Eclipse Marketplace ’ option as illustrated in Figure 1-11
Trang 20Figure 1-12 STS for Eclipse installation
Click on the ‘Install’ button alongside the STS for Eclipse tool to begin the process Follow the installation wizard Once you read the license and accept the terms click on the pop-up window’s ‘Finish’ button The STS for Eclipse tool installation process initiates Once the installation process finishes, you’ll be prompted to restart Eclipse for the changes to take effect Confirm the Eclipse restart to finish the STS for Eclipse installation
The Eclipse tool for the Spring framework is called ‘STS for Eclipse’ In the pop-up window you can scroll through the main list or type ‘sts’ in the ‘Find:’ box to limit the main list as illustrated in Figure 1-12
Trang 21With the STS for Eclipse tool you gain access to several Spring specific features not available in a regular Eclipse installation For example, to create a new Spring project from the top level ‘File’ menu select the ‘New’ and then the
‘Project’ option as illustrated in Figure 1-13
Figure 1-13 Create new Eclipse project
Trang 22A pop-up window appears to create a new project If you scroll toward the bottom you’ll see the option to create
a Spring project as illustrated in Figure 1-14 You can go ahead and create an empty application if you like, you’ll be asked for a name and to define a series of parameters which you can leave with default values
Figure 1-14 Create new Spring project in Eclipse
A more common case than creating a Spring application from scratch is to continue development of a
pre-existing Spring application Under such circumstances, the owner of an application generally distributes the application’s source code with a build script to facilitate its ongoing development
The build script of choice for most Java application is a pom.xml file designed around the build tool called Maven and more recently a build.gradle file designed around the build tool called Gradle The book’s source code and its applications are provided with Gradle build files, in addition to a single application with a Maven build file
To access Spring applications distributed with Maven or Gradle build files, it’s necessary to install additional Eclipse tools from the Eclipse Marketplace Once again you’ll need to use the Eclipse marketplace From the top level
‘Help’ menu select the ‘Eclipse Marketplace ’ option as illustrated in Figure 1-11 A pop-up window appears where you can access the Eclipse marketplace
Trang 23Figure 1-15 Maven Integration for Eclipse installation
In the ‘Find:’ box type ‘maven integration’ and you’ll see the ‘Maven Integration for Eclipse’ in the main list as illustrated in Figure 1-15 Click on the ‘Install’ button and follow the installation wizard Postpone the Eclipse restart request so you can also install Gradle Go back to the Eclipse marketplace In the ‘Find:’ box type ‘gradle’ and you’ll see the ‘Gradle Integration for Eclipse’ in the main list as illustrated in Figure 1-16 Click on the ‘Install’ button and follow the installation wizard You’ll be prompted to restart Eclipse for the changes to take effect Confirm the Eclipse restart to finish the Maven Integration for Eclipse and Gradle Integration for Eclipse installations
Trang 24Figure 1-16 Gradle Integration for Eclipse installation
Trang 25With access to both maven and gradle from Eclipse, let’s access some of the book’s applications Once you download the book’s source and unpack it to a local directory, click on the Eclipse top level ‘File’ menu and select the
‘Import ’ option A pop-up window appears In the pop-up window, click on the ‘Maven’ icon and select the ‘Existing Maven Projects’ option as illustrated in Figure 1-17
Figure 1-17 Eclipse maven import
Trang 26Notice in Figure 1-18 the ‘Projects:’ window is updated to include the line pom.xml com.apress.
springrecipes which reflects the Maven project to import Select the project checkbox and click on the ‘Finish’ button to import the project All projects in Eclipse are accessible on the left-hand side in the ‘Project Explorer’ window In this case, the project appears with the name sprintro_mvn
If you click on the project icon in the ‘Project Explorer’ window, you’ll be able to see the project structure (i.e., java classes, dependencies, configuration files, etc.).If you double click on any of the project files inside the
‘Project Explorer’, the file is opened in a separate tab in the center window alongside the dashboard Once a file is opened, you can inspect, edit, or delete its contents
Select the project icon in the ‘Project Explorer’ window and click on the right button of your mouse A contextual menu appears with various project commands Select the ‘Run as’ option followed by the ‘Maven build’ option
A pop-up window appears to edit and configure the project build Just click on the ‘Run’ button in the bottom right
In the bottom center of Eclipse you’ll see the ‘Console’ window In this case, the ‘Console’ window displays a series of build messages produced by Maven, as well as any possible errors in case the build process fails
Figure 1-18 Eclipse select maven project
Next, click on the ‘Next’ button In the following screen, on the ‘Select root directory’ line click on the ‘Browse’ button and select the directory Ch1 of the book’s source code and select sprintro_mvn as illustrated in the Figure 1-18
Trang 27You’ve just built the application, congratulations! Now let’s run it Select the project icon from the ‘Project Explorer’ window once again and press the F5 key to refresh the project directory Expand the project tree Toward the bottom you’ll see a new directory called target which contains the built application Expand the target directory by clicking on its icon Next, select the file sprintro_mvn-1.0-SNAPSHOT.jar as illustrated in Figure 1-19
Figure 1-19 Select executable in Eclipse
Trang 28Click on the ‘Run’ button in the bottom right In the bottom center of Eclipse you’ll see the ‘Console’ window In this case, the ‘Console’ window displays the application logging messages, as well as a greeting message defined by the application.
Figure 1-20 Define main executable class in Eclipse
With the file selected, click on the right button of your mouse A contextual menu appears with various project commands Select the ‘Run as’ option followed by the ‘Run configurations ’ option A pop-up window to edit and configure the run appears Ensure the ‘Java application’ option is selected on the left-hand side In the ‘Main class:’ box introduce: com.apress.springrecipes.hello.Main This is the main class for this project, as illustrated in Figure 1-20
Trang 29Next, let’s build a Gradle application with Eclipse Go to Eclipse’s top level ‘File’ menu and select the ‘Import ’ option A pop-up window appears In the pop-up window, click on the ‘Gradle’ icon and select the ‘Gradle Project’ option as illustrated in Figure 1-21.
Figure 1-21 Eclipse Gradle import
Trang 30Click on the ‘Finish’ button to import the project If you look at the left hand side of Eclipse in the ‘Project Explorer’ window you’ll see the project is loaded with the name springintro If you click on the project icon, you’ll be able to see the project structure (i.e., java classes, dependencies, configuration files, etc.).
Figure 1-22 Eclipse select Gradle subproject
Next, click on the ‘Next’ button In the following screen, in the ‘Select root directory’ line click on the ‘Browse’ button and select the top level directory of the book’s source code Next, click on the ‘Build model’ button beside the
‘Browse’ button The build model process retrieves the various Gradle subprojects contained in the book’s source code A pop-up window appears indicating the progress of the build model process Once the build model process finishes, you’ll see a list of Gradle projects, click on the project checkbox called ‘springintro’ inside ‘Ch1’ as illustrated
in Figure 1-22
Trang 31Next, click on the ‘Run’ button in the bottom right In the bottom center of Eclipse you’ll see the ‘Console’ window appear In this case, the ‘Console’ window displays a series of build messages produced by gradle, as well as any possible errors in case the build process fails.
You’ve just built the application, now let’s run it Select the project icon once again and press the F5 key to refresh the project directory Expand the project tree Toward the middle inside the build directory you’ll see a new directory called libs which contains the built application Expand the libs directory by clicking on the icon Next, select the file springintro-1.0-SNAPSHOT.jar
With the file selected, from Eclipse’s top level ‘Run’ menu select the ‘Run configurations ’ option A pop-up window appears to edit and configure the run Ensure the ‘Java application’ option is selected in the left-hand side
In the ‘Main class:’ box introduce com.apress.springrecipes.hello.Main This is the main class for this project
Figure 1-23 Eclipse select Gradle ‘build’ option
Select the project icon and click on the right button of your mouse A contextual menu appears with various project commands Select the ‘Run as’ option followed by the ‘Gradle build’ option A pop-up window appears to edit and configure the build Click on the Project/task option ‘build’ as illustrated in Figure 1-23
Trang 32Click on the ‘Run’ button in the bottom right In the bottom center of Eclipse you’ll see the ‘Console’ window In this case, the ‘Console’ window displays the application logging messages, as well as a greeting message defined by the application.
1-3 Build a Spring application with the IntelliJ IDE
on the various Spring checkboxes so IntelliJ download’s the necessary Spring dependencies for the project
To open a Spring application that uses Maven, you first need to install Maven to work from a command line interface (See Recipes 1-4) From the IntelliJ top level ‘File’ menu select the ‘Import Project’ option Next, select the Spring application based on Maven from your workstation In the next screen select the ‘Import project from external model’ option and select a ‘Maven’ type
To open a Spring application that uses Gradle, you first need to install Gradle to work from a command line interface (See Recipe 1-5) From the IntelliJ top level ‘File’ menu select the ‘Import Project’ option Next, select the Spring application based on Gradle from your workstation In the next screen select the ‘Import project from external model’ option and select a ‘Gradle’ type
How It Works
IntelliJ is one of the most popular commercial IDEs in the market Unlike other IDEs which are produced by a foundation such as Eclipse or are made to support the flagship software of a company such as STS for the Spring framework IntelliJ is produced by a company called JetBrains whose sole business is to commercialize development tools It’s this focus which makes IntelliJ particularly popular for professional developers in corporate environments
For this recipe I’ll assume you’ve already installed IntelliJ ultimate edition and just want to get up and running with Spring applications
Warning
■ intelliJ is available in a free community edition and an ultimate edition with a 30-day free trial although the free community edition provides good value for application development, the community edition does not include support for Spring applications the instructions that follow are based on the assumption that you’re using the intelliJ ultimate edition.
Trang 33To start a Spring application, in the IntelliJ ‘Quick Start’ window click on the ‘Create New Project’ link In the next window, assign a name to the project, a run-time JDK and select the ‘Java Module’ option as illustrated in Figure 1-24
Figure 1-24 IntelliJ create Spring project
Trang 34A more common case than creating a Spring application from scratch is to continue development of a pre-existing Spring application Under such circumstances, the owner of an application generally distributes the application’s source code with a build script to facilitate its ongoing development.
The build script of choice for most Java application is a pom.xml file designed around the build tool called Maven and more recently a build.gradle file designed around the build tool called Gradle The book’s source code and its applications are provided with Gradle build files, in addition to a single application with a Maven build file
Click on the ‘Next’ button In the next window, click on the various Spring checkboxes as illustrated in Figure 1-25 for IntelliJ to download the necessary Spring dependencies for the project
Figure 1-25 IntelliJ define project dependencies
Trang 35Once you download the book’s source and unpack it to a local directory, click on the IntelliJ top level ‘File’ menu and select the ‘Import Project’ option A pop-up window appears as illustrated in Figure 1-26
Figure 1-26 IntelliJ select file or directory to import
Trang 36Ensure the project checkbox is selected and click on the ‘Next’ button to import the project Next, choose the SDK version for the project Confirm the project name, location and click on the ‘Finish’ button All projects in IntelliJ are loaded on the left-hand side in the ‘Project’ window In this case, the project appears with the name springintro_mvn.
If you click on the project icon, you’ll be able to see the project structure (i.e., java classes, dependencies,
configuration files, etc.) If you double click on any of the project files inside the ‘Project’ window, the file is opened in
a separate tab in the center window You can inspect the contents of the file, as well as edit or delete its contents.Next, we need to setup Maven to work with IntelliJ Follow the instructions in Recipe 1-4 to install Maven to work from the command line Once you do this, you can setup IntelliJ to work with Maven
In the next window you’ll see the line 'com.apress.springrecipes: ' as illustrated in Figure 1-28
Figure 1-27 IntelliJ import project
Figure 1-28 IntelliJ import Maven project
Click on the directory tree presented in the pop-up window until you select the directory of the book’s source code inside Ch1 and then select springintro_mvn Click on the ‘Next’ button In the next screen select the ‘Import project from external model’ option and select a ‘Maven’ type as illustrated in Figure 1-27
Trang 37Figure 1-29 IntelliJ Maven configuration
Click on the IntelliJ top level ‘File’ menu and select the ‘Settings’ option A pop-up window appears to configure IntelliJ settings Click on the ‘Maven’ option and in the ‘Maven home directory’ introduce the Maven installation directory based on your system This is illustrated in Figure 1-29 Click on the ‘Apply’ button, followed by the ‘OK’ button
Trang 38Select the project the ‘Introduction to Spring’ line in the Maven projects window and click on the right button of your mouse A contextual menu appears with various commands for the project Select the ‘Run Maven Build’ option
In the bottom center of IntelliJ you’ll see the ‘Run’ window appear In this case, the ‘Run’ window displays a series of build messages produced by Maven, as well as any possible errors in case the build process fails
Warning
■ if you see the error message ‘no valid maven installation found either set the home directory in the configuration dialog or set the m2_home environment variable on your system’ it means maven is not being found by intelliJ verify the maven installation and configuration process.
Figure 1-30 IntelliJ Maven projects window
Next, on the right-hand side of IntelliJ click on the vertical tab ‘Maven projects’ to show the Maven project window as illustrated in Figure 1-30
Trang 39You’ve just built the application, congratulations! Now let’s run it By default, IntelliJ hides the target directory created by Maven to place the built application You’ll need to deactivate this behavior in order to run the application directly from IntelliJ Click on the IntelliJ top level ‘File’ menu and select the ‘Settings’ option A pop-up window appears to configure IntelliJ settings Double click on the ‘Maven’ option and click on the ‘Importing’ sub-option Uncheck the box ‘Exclude build directory’ as illustrated in Figure 1-31 Click on the ‘Apply’ button and then click on the ‘OK’ button
Figure 1-31 IntelliJ Maven show build directory
Trang 40Figure 1-32 IntelliJ select application to run
With this last change you’ll see the target directory in the ‘Project’ window If you don’t see the target directory click the Ctrl+Alt+Y key combination to synchronize the project Expand the target directory by clicking on its icon Next, select the file springintro_mvn-1.0-SNAPSHOT.jar as illustrated in Figure 1-32