0% found this document useful (0 votes)
60 views22 pages

Lab 2.1: Java-Based Configuration

Here are the key points about bean scopes: - By default, Spring beans have singleton scope - only one instance is created per Spring container. - Changing the catalog bean to prototype scope means a new instance will be created each time it is requested from the container. - The @PostConstruct annotation allows running code after the bean is constructed but before it is used. This lets us print a message to verify instance creation. - With prototype scope, two distinct instances are returned from the container, so the assert passes. With singleton, the same instance is returned both times, causing the assert to fail. - Different scopes like request, session etc are useful for web-based applications to control object lifetimes.

Uploaded by

darwinvargas2011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views22 pages

Lab 2.1: Java-Based Configuration

Here are the key points about bean scopes: - By default, Spring beans have singleton scope - only one instance is created per Spring container. - Changing the catalog bean to prototype scope means a new instance will be created each time it is requested from the container. - The @PostConstruct annotation allows running code after the bean is constructed but before it is used. This lets us print a message to verify instance creation. - With prototype scope, two distinct instances are returned from the container, so the assert passes. With singleton, the same instance is returned both times, causing the assert to fail. - Different scopes like request, session etc are useful for web-based applications to control object lifetimes.

Uploaded by

darwinvargas2011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Lab 2.

1: Java-based Configuration

In this lab, we will use @Configuration classes to


configure all our beans and
dependencies
LAB
SYNOPSI Lab


S
Overview: In this lab, we will use Spring's Java-based
configuration to configure our beans and dependencies
– Providing Java-only metadata (no XML at all)
– We'll create a separate @Configuration class for each
tier
• We have many options here !
– We will import Java-based configurations into one root
configuration

 Builds on previous labs: none

 Approximate Time: 25-45 minutes (depending on optional


parts)

Lab 2.1: Java-based Config 2


LAB
PREPARATI Lab


ON
The new root lab directory where you will do all your work is:
workspace\Lab02.1
 This lab contains no XML
– All configuration metadata will be written in Java - The safer
XML!
– Also, metadata will be external to our domain model

Tasks to Perform
 Close all open files and projects
 Create a new Java project called Lab02.1 in the workspace *
– See Lab 1.1 instructions on how to do this if you need to
– Remember to add the Spring user libraries
 Don't worry about errors (Red x’s) and warnings
– They'll soon disappear
Lab 2.1: Java-based Config 3
DOMAIN Lab
MODEL

Lab 2.1: Java-based Config 4


DEFINE ROOT Lab
CONFIGURATION CLASS
Tasks to Perform
 We supply the following configuration classes in this lab
– SpringConfig: It imports the other configuration classes
• It is the collector of the other classes that have bean defs in them
• This allows us to bootstrap Spring with a single class!
– SpringRepositoryConfig, and SpringServicesConfig
contain bean definitions
– Ignore SpringDomainConfig for now - it's used later

 Open SpringConfig.java for editing


– Add the @Configuration annotation to the class
– Add the @ComponentScan annotation with "com.javatunes" as the
base packages
– @Import the 2 Java config classes we'll use now
(repository/service) (1)

Lab 2.1: Java-based Config 5


JAVA-BASED Lab
CONFIGURATION
Tasks to Perform
 For the bean defs and wiring, look at the UML earlier in the lab
– We have ItemRepository and Catalog implementations
• And CatalogImpl needs an ItemRepository
– We'll define/wire all of these using the @Configuration style (1)
• We've removed the @Component/@Autowired annotations from our
types for this lab

 Open SpringRepositoryConfig.java for editing


– Add the @Configuration annotation to the class

 Add an @Bean definition that returns an ItemRepository


– It should be named itemRepository
– Return an instance or our InMemoryItemRepository class

 The item repository definition is the only @Bean in this class


Lab 2.1: Java-based Config 6
JAVA-BASED Lab
CONFIGURATION
Tasks to Perform
 Open SpringServicesConfig.java for editing
– Add @Configuration to the class
– Note that we have a repository property of type ItemRepository
– Use @Autowired to inject the repository

 Add an @Bean definition that returns a Catalog


– Return an instance of our CatalogImpl class
– Set its repository instance using the injected repository
• Again - that is normal Java code using the (injected) repository variable in
the class
– This is the only @Bean in this configuration class

Lab 2.1: Java-based Config 7


FINISH TEST
PROGRAM AND Lab


RUN Tasks to Perform
Open CatalogTest for editing
– You need to create the application context in both test methods
– It's an AnnotationConfigApplicationContext now, since you're
using @Configuration style

 Run CatalogTest as a JUnit Test


– All tests should pass (they are the same as the last lab)
– You should see items printed out due to the lookup in the test
– Up to InMemoryItemRepository.maxSearchResults, which
defaults to 30 items

Lab 2.1: Java-based Config 8


[OPTIONAL] JAVA CODE Lab
IN CONFIGTasks
CLASSto Perform
 [Optionally] We can put other Java code in a config class
– All Java's power is available, as we'll show here
– The metadata Java code may not be executed “directly” but it is
indirectly executed, and we can use it !

 Open SpringDomainConfig.java for editing


– Add the @Configuration annotation to the class
– Add @Bean to the existing maxSearchResults() method
• Note how it contains simple code returning a randomly generated
Integer
• It could be a more complex calculation, doing whatever we wanted

 Open SpringConfig.java for editing


(1)
– Add SpringDomainConfig to the list of imported configuration
classes
Lab 2.1: Java-based Config 9
[OPTIONAL] INJECT THE Lab
INTEGER VALUE
Tasks to Perform
 Open SpringRepositoryConfig.java for editing:
– We'll set a field in the repository using an injected value
– We could do this differently (1)
 Add a private Integer field called maxSearchResults
– Annotate it with @Autowired to initialize it
• This will inject the value configured in SpringDomainConfig (2)

 Do the following in the @Bean def returning an ItemRepository


– After creating the InMemoryItemRepository, set its
maxSearchResults property
• Use the maxSearchResults field you just injected into the config class
– Return the repository instance as before
 Run CatalogTest as a JUnit Test again
– You should see a random number of Items returned each time you run
the test
Lab 2.1: Java-based Config 10
SUMM Lab

 ARY
Java based configurations provide you with the best-of-breed
style of specifying your application requirements.
– It’s Java code so IDE support is mature and solid
– You effectively write the code you have always written to satisfy
dependencies
• But not in your application code!
– You can have logic that determines what happens in real-time
– And refactoring and cross-referencing is clean and simple

 This has a good chance of become the preferred technique


– With XML being used narrowly, and annotations used to
eliminate ambiguities (covered next)
– The Spring project now recommends this

 It’s evolution ! STOP

Lab 2.1: Java-based Config 11


Lab 2.2: Bean Lifecycle

In this lab, we will work with the bean lifecycle


LAB
SYNOPSI Lab


S
Overview: In this lab, we will work with the bean lifecycle
– Explore and configure different bean scopes
– Work with some of the bean lifecycle callbacks and the interfaces
Spring provides to work with them

 Builds on previous labs: Lab 2.1


– Continue working in your Lab02.1 project

 Approximate Time: 20-30 minutes

Lab 2.2: Bean Lifecycle 13


PROTOTYP Lab
E SCOPE Tasks to Perform
 Open SpringServicesConfig for editing
– Change the scope of the catalog bean to prototype
– Open CatalogTest and in testCatalogLookupPositive() get
a second catalog
Catalog catalog2 = ctx.getBean(Catalog.class);
– Add an assertTrue that asserts (catalog != catalog2)
• We've imported all the assert methods already (via import static)

 Run the tests, make sure that they pass


 Add a creation lifecycle callback
– Open CatalogImpl for editing
– Add a method public void init() { … }
– Annotate it with @PostConstruct
– In the method, just print out something using
System.out.println()
Lab 2.2: Bean Lifecycle 14
BEAN
LIFECYCL Lab


E Tasks to Perform
Run CatalogTest again
– Go to the console view in Eclipse - do you see any output?
– How many catalogs were created?

 In SpringServicesConfig.java, remove the prototype scoping on


the catalog
– Run the tests again - this time you should have one failure on the assert
of catalog != catalog2
– Why? What is default scope of a Spring managed bean?
– Remove the assert for this in CatalogTest, and run it again (1)
– Does it pass? How many catalogs are created?
– That's it - you've used the lifecycle methods to see how scoping works !

STOP

Lab 2.2: Bean Lifecycle 15


Lab 2.3: Profiles

In this lab, we will use profiles to customize our


definitions for different
environments
LAB
SYNOPSI Lab


S
Overview: In this lab, we will create profiles to customize our
bean definitions
– We'll create two profiles that have different configurations, then
test both of them
– We'll also (optionally) try out inheritance in @Configuration
classes

 Builds on previous labs: none

 Approximate Time: 20-45 min. (Depending on optional


parts)

Lab 2.3: Profiles 17


LAB
PREPARATI Lab


ON
The new root lab directory where you will do all your work is:
workspace\Lab02.3

Tasks to Perform
 Close all open files and projects

 Create a new Java project called Lab02.3 in the workspace *


– See Lab 1.1 instructions on how to do this if you need to
– Remember to add the Spring user library

 Note: This lab combines @Bean style bean definition and


@Autowired style DI with @Configuration style configuration

Lab 2.3: Profiles 18


SET UP Lab
PROFILES Tasks to Perform
 Open SpringDevRepositoryConfig in
com.javatunes.config for editing
– Annotate it to be profile "dev" (1)
– Finish the itemRepository() method
• Create an instance of InMemoryItemRepository
• Set the maxSearchResults with the value from the
autowired property above
• Return the instance

 Repeat similar steps in SpringProdRepositoryConfig


– Annotate it to be profile "prod"
– Create a ProductionRepository instance in
itemRepository()
– Return the instance

Lab 2.3: Profiles 19


ACTIVATE AND Lab
TEST PROFILES
Tasks to Perform
 Open CatalogTest in the test folder for editing
– Review a test method to see how it calls setupContext()
– Find the setupContext() method near the top - it sets up the profile
and reads the config class for all the test methods
– Set the active profile to the passed in profile name
– Register the configuration class that was passed in
– Refresh the context and save your changes

–Review the rest of the test class - it has test methods for both the dev
and production profiles
 Run CatalogTest as a JUnit Test
– You should see output from both profiles (1)

 Congratulations! You have switched between two different


profiles.
Lab 2.3: Profiles 20
[OPTIONAL] ACTIVE Lab
PROFILE VIA
Tasks PROPERTY
to Perform
 [Optional] Use a different method of setting the active profile
– First comment out the setting of the active profile in the dev test case (
– Run the test and see how it works
– It should fail, since the catalog bean won't be defined if none of the
profiles is active

 Set the profile to "dev" using the spring.profiles.active


property
– You can set this as a VM property in the Run Configuration (1)

 Run the test case again


– You should see output indicating the appropriate profile was
selected

Lab 2.3: Profiles 21


[OPTIONAL-2]
Lab
@CONFIGURATION
INHERITANCE

Tasks to Perform
Review the two repository config classes
– Do you see any commonality that you can factor out into a base class
• Review the inheritance example in the manual slides for ideas
• It's OK if it's very simple - we purposely keep the types simple

 Create an @Configuration class -


SpringBaseRepositoryConfig
– Put the common code from the two configuration classes in it
– Add any new needed code to this base class

 Modify the other two config classes to extend the base class
– Remove the common code from both types
– Add to or modify these two config classes to work correctly

 Run the test case again


– All tests should still pass STOP

Lab 2.3: Profiles 22

You might also like