SlideShare a Scribd company logo
1 of 14
SPRING ESSENTIALS 2
Bean Scopes, Profiles, Testing.
(Spring Series 02)
Presenter: Heartin Jacob Kanikathottu
TOPICS
• Bean Scopes
• Initialization and Destruction Code for a Spring Bean
• Spring Profiles
• JUNIT Testing of code with Profiles
• Introduction to Spring Boot
• What Next?
BEAN SCOPES IN SPRING
• Beans in Spring can be either singletons or prototypes:
• Singleton: one instance of the bean will be maintained by the Spring and will be returned
every time you call the getBean() method.
• Prototype: A new bean will be created every time you call the getBean() method.
• The default is singleton.
• In Java configuration, you can specify that a bean scope is prototype by specifying:
• @Scope("prototype") over the bean definition.
BEAN SCOPE EXAMPLE
• Example Bean Class:
• class JJWriter {
private String content="default";
//getters and setters
• }
• TODO:
• Create a Java configuration class.
• Test below with and without @Scope("prototype") over the bean definition
• Get bean, change content, get again and verify (in the test method or main method).
INITIALIZATION AND DESTRUCTION CODE
• Using initMethod and destroyMethod attributes of the @Bean annotation
• Advantage: We do not need source code access to component classes.
• Limitation: We cannot specify methods that accept any parameters
• Using PostConstruct and PreDestroy from javax.annotation package
• Advantage: These are standard Java annotations
• Limitation: We need to add annotations to the source code and hence need source code
access
EXAMPLE: INITIALIZATION AND
DESTRUCTION CODE
• Example 1: initMethod and destroyMethod attributes of @Bean
• @Bean (name = "jjwriter", initMethod="initMethod", destroyMethod="destroyMethod")
public JJWriter getJJWriter()
…
• Example 2: PostConstruct and PreDestroy
• @PostConstruct
public void initMethod() {
…
@PreDestroy
public void destroyMethod() {
…
SPRING PROFILES
• Can have @Profile at bean level or a @Configuration class level
• Can specify @Profile along with @Component
• You can specify the profile name as "default" to enable it as default:
• @Profile({"default","dbprofile"})
• Profiles can be activated using different ways such as system property, annotation,
web application context parameter etc.
• With xml configuration, you can use the beans element along with its attributes
profile and primary, and enclose the beans to add them to that scope.
EXAMPLE: SPRING PROFILES
• Config Class:
• @Configuration
public class DemoConfig {
@Bean (name = "writer")
@Profile({"default","dbprofile"})
…
@Bean (name = "writer")
@Profile("fileprofile")
public JJWriter getJJFileWriter()
…
• Test Class:
• AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("fileprofile");
context.register(DemoConfig.class);
context.refresh();
DIFFERENT WAYS TO ACTIVATE PROFILES
• setActiveProfiles method
• context.getEnvironment().setActiveProfiles("fileprofile");
• System property
• System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
"dbprofile, fileprofile");
• spring.profiles.active context parameter
• spring.profiles.active property
• @ActiveProfiles annotation (From within JUnit tests)
JNUIT TESTING
• You should place your test classes inside the src/test/java folder in a package similar to
your original classes.
• Any files that needs to be read from classpath has to be placed in src/test/resources
folder.
• We can enable profiles from within a JUNIT test using @ActiveProfiles annotation.
• Test specific config class and properties file is preferred:
• @Configuration
@PropertySource("classpath:/test.properties")
@ComponentScan(basePackages="com.javajee.spring")
public class TestConfig {
}
JNUIT TESTING
• Dependencies: spring-test and junit
• Example Test Class:
• @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
@ActiveProfiles("dbprofile")
public class JJDatabaseWriterTest {
@Autowired
JJWriter jjwriter;
@Test
public void testJJDatabaseWriterToString()
{
Assert.assertEquals("Writing to Database!!!", jjwriter.toString());
}
}
INTRO TO SPRING BOOT
• Spring boot takes an opinionated view of the Spring platform and third-party libraries,
for building production-ready Spring applications. Spring Boot favors convention over
configuration and is designed to get you up and running as quickly as possible.
• Important features, as listed, are:
• Create stand-alone Spring applications
• Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
• Provide opinionated 'starter' POMs to simplify your Maven configuration
• Automatically configure Spring whenever possible
• Provide production-ready features such as metrics, health checks and externalized
configuration
• Absolutely no code generation and no requirement for XML configuration
WHAT NEXT?
• Please complete doing examples for all concepts mentioned.
• We will learn about Spring MVC, Spring REST, Spring Data and eventually go deep
with Spring Boot.
RESOURCES & REFERENCES
• https://spring.io/docs
• http://javajee.com/spring-framework-4-essentials

More Related Content

What's hot

Spring training
Spring trainingSpring training
Spring trainingshah_d_p
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformBozhidar Bozhanov
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15aminmesbahi
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformArun Gupta
 
Web Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data ValidationWeb Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data ValidationWebsecurify
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injectionsrmelody
 
Java component
Java componentJava component
Java componentkrishashi
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10minCorneil du Plessis
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization Hitesh-Java
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to javamanish kumar
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkRaveendra R
 
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Roman Zenner
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScriptLilia Sfaxi
 
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMAsynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMHugh Anderson
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transferAnkit Desai
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...Jorge Hidalgo
 

What's hot (20)

Spring training
Spring trainingSpring training
Spring training
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platform
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 Platform
 
Web Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data ValidationWeb Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data Validation
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Java component
Java componentJava component
Java component
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
JDBC
JDBCJDBC
JDBC
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMAsynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 

Viewers also liked

AHundredFishinaTank-LolitaBeylina
AHundredFishinaTank-LolitaBeylinaAHundredFishinaTank-LolitaBeylina
AHundredFishinaTank-LolitaBeylinaLolita Beylina
 
Linkedin Presentation Krysyian Gnysinski
Linkedin Presentation Krysyian GnysinskiLinkedin Presentation Krysyian Gnysinski
Linkedin Presentation Krysyian GnysinskiKrystian Gnysinski
 
La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...
La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...
La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...Andra Solanyi Bonilla Carabali
 
Alexandra Knopp resume vitae
Alexandra Knopp resume vitaeAlexandra Knopp resume vitae
Alexandra Knopp resume vitaeAlexandra Knopp
 
MEAN - A Stack That Drives Digital Transformation
MEAN - A Stack That Drives Digital TransformationMEAN - A Stack That Drives Digital Transformation
MEAN - A Stack That Drives Digital TransformationJK Tech
 
Cyber Security for Digital-Era
Cyber Security for Digital-EraCyber Security for Digital-Era
Cyber Security for Digital-EraJK Tech
 
Dilg memorandum circular no. 2016 116
Dilg memorandum circular no. 2016 116Dilg memorandum circular no. 2016 116
Dilg memorandum circular no. 2016 116bituko butiki
 
Cyber security threats for 2017
Cyber security threats for 2017Cyber security threats for 2017
Cyber security threats for 2017Ramiro Cid
 

Viewers also liked (11)

AHundredFishinaTank-LolitaBeylina
AHundredFishinaTank-LolitaBeylinaAHundredFishinaTank-LolitaBeylina
AHundredFishinaTank-LolitaBeylina
 
Linkedin Presentation Krysyian Gnysinski
Linkedin Presentation Krysyian GnysinskiLinkedin Presentation Krysyian Gnysinski
Linkedin Presentation Krysyian Gnysinski
 
La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...
La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...
La mirada pedagógica para el siglo xxi  teorías , temas y prácticas en cuesti...
 
Alexandra Knopp resume vitae
Alexandra Knopp resume vitaeAlexandra Knopp resume vitae
Alexandra Knopp resume vitae
 
имею право иметь права
имею право иметь праваимею право иметь права
имею право иметь права
 
CV-R.B.Guinir Jr.(01-15-17)
CV-R.B.Guinir Jr.(01-15-17)CV-R.B.Guinir Jr.(01-15-17)
CV-R.B.Guinir Jr.(01-15-17)
 
MEAN - A Stack That Drives Digital Transformation
MEAN - A Stack That Drives Digital TransformationMEAN - A Stack That Drives Digital Transformation
MEAN - A Stack That Drives Digital Transformation
 
Cyber Security for Digital-Era
Cyber Security for Digital-EraCyber Security for Digital-Era
Cyber Security for Digital-Era
 
Dilg memorandum circular no. 2016 116
Dilg memorandum circular no. 2016 116Dilg memorandum circular no. 2016 116
Dilg memorandum circular no. 2016 116
 
License
LicenseLicense
License
 
Cyber security threats for 2017
Cyber security threats for 2017Cyber security threats for 2017
Cyber security threats for 2017
 

Similar to Spring essentials 2 Spring Series 02)

Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qconYiwei Ma
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragonAyushman Jain
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHBhavsingh Maloth
 
Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019graemerocher
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej Mihályi
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxDrYogeshDeshmukh1
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design PatternsAlex Theedom
 
Spring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsSpring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsVMware Tanzu
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injectionRajiv Gupta
 
Effiziente persistierung
Effiziente persistierungEffiziente persistierung
Effiziente persistierungThorben Janssen
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns Alex Theedom
 
PRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.comPRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.comMcdonaldRyan108
 
A Dexterity Intro for Recovering Archetypes Addicts
A Dexterity Intro for Recovering Archetypes AddictsA Dexterity Intro for Recovering Archetypes Addicts
A Dexterity Intro for Recovering Archetypes AddictsDavid Glick
 
Spring framework IOC and Dependency Injection
Spring framework  IOC and Dependency InjectionSpring framework  IOC and Dependency Injection
Spring framework IOC and Dependency InjectionAnuj Singh Rajput
 

Similar to Spring essentials 2 Spring Series 02) (20)

Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Java beans
Java beansJava beans
Java beans
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
 
Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019Micronaut Deep Dive - Devoxx Belgium 2019
Micronaut Deep Dive - Devoxx Belgium 2019
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
 
Java EE Revisits Design Patterns
Java EE Revisits Design PatternsJava EE Revisits Design Patterns
Java EE Revisits Design Patterns
 
Spring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden GemsSpring Framework 5.0: Hidden Gems
Spring Framework 5.0: Hidden Gems
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injection
 
Effiziente persistierung
Effiziente persistierungEffiziente persistierung
Effiziente persistierung
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns
 
PRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.comPRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.com
 
Spock
SpockSpock
Spock
 
A Dexterity Intro for Recovering Archetypes Addicts
A Dexterity Intro for Recovering Archetypes AddictsA Dexterity Intro for Recovering Archetypes Addicts
A Dexterity Intro for Recovering Archetypes Addicts
 
Spring framework IOC and Dependency Injection
Spring framework  IOC and Dependency InjectionSpring framework  IOC and Dependency Injection
Spring framework IOC and Dependency Injection
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Spring essentials 2 Spring Series 02)

  • 1. SPRING ESSENTIALS 2 Bean Scopes, Profiles, Testing. (Spring Series 02) Presenter: Heartin Jacob Kanikathottu
  • 2. TOPICS • Bean Scopes • Initialization and Destruction Code for a Spring Bean • Spring Profiles • JUNIT Testing of code with Profiles • Introduction to Spring Boot • What Next?
  • 3. BEAN SCOPES IN SPRING • Beans in Spring can be either singletons or prototypes: • Singleton: one instance of the bean will be maintained by the Spring and will be returned every time you call the getBean() method. • Prototype: A new bean will be created every time you call the getBean() method. • The default is singleton. • In Java configuration, you can specify that a bean scope is prototype by specifying: • @Scope("prototype") over the bean definition.
  • 4. BEAN SCOPE EXAMPLE • Example Bean Class: • class JJWriter { private String content="default"; //getters and setters • } • TODO: • Create a Java configuration class. • Test below with and without @Scope("prototype") over the bean definition • Get bean, change content, get again and verify (in the test method or main method).
  • 5. INITIALIZATION AND DESTRUCTION CODE • Using initMethod and destroyMethod attributes of the @Bean annotation • Advantage: We do not need source code access to component classes. • Limitation: We cannot specify methods that accept any parameters • Using PostConstruct and PreDestroy from javax.annotation package • Advantage: These are standard Java annotations • Limitation: We need to add annotations to the source code and hence need source code access
  • 6. EXAMPLE: INITIALIZATION AND DESTRUCTION CODE • Example 1: initMethod and destroyMethod attributes of @Bean • @Bean (name = "jjwriter", initMethod="initMethod", destroyMethod="destroyMethod") public JJWriter getJJWriter() … • Example 2: PostConstruct and PreDestroy • @PostConstruct public void initMethod() { … @PreDestroy public void destroyMethod() { …
  • 7. SPRING PROFILES • Can have @Profile at bean level or a @Configuration class level • Can specify @Profile along with @Component • You can specify the profile name as "default" to enable it as default: • @Profile({"default","dbprofile"}) • Profiles can be activated using different ways such as system property, annotation, web application context parameter etc. • With xml configuration, you can use the beans element along with its attributes profile and primary, and enclose the beans to add them to that scope.
  • 8. EXAMPLE: SPRING PROFILES • Config Class: • @Configuration public class DemoConfig { @Bean (name = "writer") @Profile({"default","dbprofile"}) … @Bean (name = "writer") @Profile("fileprofile") public JJWriter getJJFileWriter() … • Test Class: • AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.getEnvironment().setActiveProfiles("fileprofile"); context.register(DemoConfig.class); context.refresh();
  • 9. DIFFERENT WAYS TO ACTIVATE PROFILES • setActiveProfiles method • context.getEnvironment().setActiveProfiles("fileprofile"); • System property • System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dbprofile, fileprofile"); • spring.profiles.active context parameter • spring.profiles.active property • @ActiveProfiles annotation (From within JUnit tests)
  • 10. JNUIT TESTING • You should place your test classes inside the src/test/java folder in a package similar to your original classes. • Any files that needs to be read from classpath has to be placed in src/test/resources folder. • We can enable profiles from within a JUNIT test using @ActiveProfiles annotation. • Test specific config class and properties file is preferred: • @Configuration @PropertySource("classpath:/test.properties") @ComponentScan(basePackages="com.javajee.spring") public class TestConfig { }
  • 11. JNUIT TESTING • Dependencies: spring-test and junit • Example Test Class: • @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TestConfig.class }) @ActiveProfiles("dbprofile") public class JJDatabaseWriterTest { @Autowired JJWriter jjwriter; @Test public void testJJDatabaseWriterToString() { Assert.assertEquals("Writing to Database!!!", jjwriter.toString()); } }
  • 12. INTRO TO SPRING BOOT • Spring boot takes an opinionated view of the Spring platform and third-party libraries, for building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible. • Important features, as listed, are: • Create stand-alone Spring applications • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files) • Provide opinionated 'starter' POMs to simplify your Maven configuration • Automatically configure Spring whenever possible • Provide production-ready features such as metrics, health checks and externalized configuration • Absolutely no code generation and no requirement for XML configuration
  • 13. WHAT NEXT? • Please complete doing examples for all concepts mentioned. • We will learn about Spring MVC, Spring REST, Spring Data and eventually go deep with Spring Boot.
  • 14. RESOURCES & REFERENCES • https://spring.io/docs • http://javajee.com/spring-framework-4-essentials