Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
SPRING COOKBOOK
SPRING COOKBOOK

SPRING COOKBOOK: Over 100 hands-on recipes to build Spring web applications easily and efficiently

Arrow left icon
Profile Icon Jerome Jaglale Profile Icon Yilmaz
Arrow right icon
zł59.99 zł158.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (3 Ratings)
eBook May 2015 234 pages 1st Edition
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jerome Jaglale Profile Icon Yilmaz
Arrow right icon
zł59.99 zł158.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (3 Ratings)
eBook May 2015 234 pages 1st Edition
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

SPRING COOKBOOK

Chapter 2. Defining Beans and Using Dependency Injection

In this chapter, we will cover the following recipes:

  • Defining a bean explicitly with @Bean
  • Defining a bean implicitly with @Component
  • Using a bean via dependency injection with @Autowired
  • Using a bean directly
  • Listing all beans
  • Using multiple configuration classes

Introduction

Beans are at the core of Spring. They are standard Java objects instantiated and managed by Spring.

Beans are mostly used to:

  • Configure Spring in some way (database connection parameters, security, and so on)
  • Avoid hardcoding dependencies using dependency injection, so that our classes remain self-contained and unit testable

In this chapter, you'll learn how to define beans and use them.

Defining a bean explicitly with @Bean

The simplest way to define a bean is to create, in a Spring configuration class, a method annotated with @Bean returning an object (the actual bean). Such beans are usually used to configure Spring in some way (database, security, view resolver, and so on). In this recipe, we'll define a bean that contains the connection details of a database.

How to do it…

In a Spring configuration class, add a dataSource() method annotated with @Bean and return a Datasource object. In this method, create a DriverManagerDataSource object initialized with the connection details of a database:

@Bean
public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/db1");
        dataSource.setUsername("root");
        dataSource.setPassword("123");
 ...

Defining a bean implicitly with @Component

Beans don't have to be defined in a Spring configuration class. Spring will automatically generate a bean from any class annotated with @Component.

Getting ready

We will use the basic web application created in the Creating a Spring web application recipe in Chapter 1, Creating a Spring Application.

Create the com.springcookbook.service package and the following service class in it:

public class UserService {
  public int findNumberOfUsers() {
    return 10;
  }
}

How to do it…

Here are the steps to define a bean by adding @Component to an existing class:

  1. In the Spring configuration file, in the @ComponentScan class annotation, add the com.springcookbook.service base package:
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = {"com.springcookbook.controller", "com.springcookbook.service"})
    public class AppConfig {  
    }
  2. In the UserService class, add @Component:
    @Component
    public class UserService {
      public int findNumberOfUsers...

Using a bean via dependency injection with @Autowired

Spring configuration beans, such as the one in the Defining a bean explicitly with @Bean recipe are automatically discovered and used by Spring. To use a bean (any kind of bean) in one of your classes, add the bean as a field and annotate it with @Autowired. Spring will automatically initialize the field with the bean. In this recipe, we'll use an existing bean in a controller class.

Getting ready

We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService bean.

How to do it…

Here are the steps to use an existing bean in one of your classes:

  1. In the controller class, add a UserService field annotated with @Autowired:
    @Autowired
    UserService userService;
  2. In a controller method, use the UserService field:
    @RequestMapping("hi")
    @ResponseBody
    public String hi() {
      return "nb of users: " + userService.findNumberOfUsers();
    }
  3. In a web browser, go to http://localhost:8080...

Using a bean directly

It's possible to get a bean directly from Spring instead of using dependency injection by making Spring's ApplicationContext, which contains all the beans, a dependency of your class. In this recipe, we'll inject an existing bean into a controller class.

Getting ready

We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService bean.

How to do it…

Here are the steps to get and use a bean directly:

  1. In the controller class, add an ApplicationContext field annotated with @Autowired:
    @Autowired
    private ApplicationContext applicationContext;
  2. In a controller method, use the ApplicationContext object and its getBean() method to retrieve the UserService bean:
    UserService userService = (UserService)applicationContext.getBean("userService");        

How it works…

When the controller class is instantiated, Spring automatically initializes the @Autowired field with its ApplicationContext object. The...

Listing all beans

It can be useful, especially for debugging purposes, to list all the beans at a given moment.

Getting ready

We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService bean.

How to do it…

Here are the steps to retrieve the names of the beans currently in Spring's ApplicationContext object:

  1. In your class, add an ApplicationContext field annotated with @Autowired:
    @Autowired
    private ApplicationContext applicationContext;
  2. In a method of that class, use ApplicationContext and its getBeanDefinitionNames()method to get the list of bean names:
    String[] beans = applicationContext.getBeanDefinitionNames();
    for (String bean : beans) {
      System.out.println(bean);
    }  

How it works…

When the controller class is instantiated, Spring automatically initializes the @Autowired field with its ApplicationContext object. The ApplicationContext object references all Spring beans, so we can get a list of all the beans that are using...

Introduction


Beans are at the core of Spring. They are standard Java objects instantiated and managed by Spring.

Beans are mostly used to:

  • Configure Spring in some way (database connection parameters, security, and so on)

  • Avoid hardcoding dependencies using dependency injection, so that our classes remain self-contained and unit testable

In this chapter, you'll learn how to define beans and use them.

Left arrow icon Right arrow icon

Description

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.

Who is this book for?

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.

What you will learn

  • Install Maven and Tomcat and create a Spring MVC web application
  • Display, validate, and process forms
  • Query a database with minimal code
  • Authenticate users and manage their roles
  • Build REST, Java RMI, and Hessian web services
  • Create and schedule batch jobs
  • Offer customized page layouts to mobiles and tablets
  • Exchange data with Facebook and Twitter

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 25, 2015
Length: 234 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985814
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 25, 2015
Length: 234 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985814
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 529.97
Mastering Spring Application Development
zł189.99
Spring Boot Cookbook
zł141.99
SPRING COOKBOOK
zł197.99
Total 529.97 Stars icon

Table of Contents

13 Chapters
1. Creating a Spring Application Chevron down icon Chevron up icon
2. Defining Beans and Using Dependency Injection Chevron down icon Chevron up icon
3. Using Controllers and Views Chevron down icon Chevron up icon
4. Querying a Database Chevron down icon Chevron up icon
5. Using Forms Chevron down icon Chevron up icon
6. Managing Security Chevron down icon Chevron up icon
7. Unit Testing Chevron down icon Chevron up icon
8. Running Batch Jobs Chevron down icon Chevron up icon
9. Handling Mobiles and Tablets Chevron down icon Chevron up icon
10. Connecting to Facebook and Twitter Chevron down icon Chevron up icon
11. Using the Java RMI, HTTP Invoker, Hessian, and REST Chevron down icon Chevron up icon
12. Using Aspect-oriented Programming Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(3 Ratings)
5 star 66.7%
4 star 0%
3 star 0%
2 star 33.3%
1 star 0%
Tapuz Jul 12, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book covers a wide range of base usecases and situations a developer has to face every day with Spring.Examples are clear and concise and very useful both to junior programmers to find how to do something and to senior to use as reference or to have bases to modify for living code.Very useful tool for having in one place numerous code examples and save time and doubts .
Amazon Verified review Amazon
George Victor Jul 03, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A nice book to learn the basics of spring framework. The recipes are concise and clear, and easy to follow. And covers a variety of topics such as spring security, mobile, social, AOP, UTs etc. Would have been even nicer if some really advanced recipes are also included, though I would give five stars for this book without a second thought for helping me in learning the basics of spring.
Amazon Verified review Amazon
han liu Jan 27, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
this book is not for new starter but some one with experience.(since it is named cookbook)there is no explanation of any concept and i found that most of time i have to do a lot of research in order to understand of the code.this cook book mostly use annotation.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.