Hi, I just prepared a presentation on Java Spring Framework, the topics covered include architecture of Spring framework and it's modules. Spring Core is explained in detail including but not limited to Inversion of Control (IoC), Dependency Injection (DI) etc. Thank you and happy learning. :)
In this Java Spring Training session, you will learn Spring – Inversion of Control, Dependency Injection and Bean definitions. Topics covered in this session are:
For more information, visit this link:
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
University of Colorado PhD software engineering student Aaron Schram explains the details of creating a web applications using the Spring MVC framework
Building a REST Service in minutes with Spring BootOmri Spector
A walk through building a micro service using Spring Boot.
Deck presented at Java 2016
Source accompanying presentation can be found at https://github.com/ospector/sbdemo
In this Java Spring Training session, you will learn Spring – Inversion of Control, Dependency Injection and Bean definitions. Topics covered in this session are:
For more information, visit this link:
Spring Framework
• Core Container
• Data Access/Integration
• Web Layer
• Spring Setup
• Key features
• Spring Bean
• Dependency Injection
• Relation between DI and IoC
• Spring IoC Containers
• Spring DI
https://www.mindsmapped.com/courses/software-development/spring-fundamentals-learn-spring-framework-and-spring-boot/
University of Colorado PhD software engineering student Aaron Schram explains the details of creating a web applications using the Spring MVC framework
Building a REST Service in minutes with Spring BootOmri Spector
A walk through building a micro service using Spring Boot.
Deck presented at Java 2016
Source accompanying presentation can be found at https://github.com/ospector/sbdemo
Welcome to presentation on Spring boot which is really great and relatively a new project from Spring.io. Its aim is to simplify creating new spring framework based projects and unify their configurations by applying some conventions. This convention over configuration is already successfully applied in so called modern web based frameworks like Grails, Django, Play framework, Rails etc.
JOHN HUMPHREYS VP OF ENGINEERING INFRASTRUCTURE SYSTEMS, NOMURA
Spring Boot is a modern and extensible development framework that aims (and succeeds!) to take as much pain as possible out of developing with Java. With just a few Maven dependencies, new or existing programs become runnable, init.d-compliant uber-JARs or uber-WARs with embedded web-servers and virtually zero-configuration, code or otherwise. As an added freebie, Spring Boot Actuator will provide your programs with amazing configuration-free production monitoring facilities that let you have RESTFUL endpoints serving live stack-traces, heap and GC statistics, database statuses, spring-bean definitions, and password-masked configuration file audits.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
This presentation is about Spring MVC. Topics covered in this session are:
1. HTTP Servlet
2. What is Spring MVC?
3. MVC Architecture
4. Request Processing Workflow in Spring MVC
5. Spring Web Application Context
6. Spring MVC Configuration
7. Important Annotations
This presentation provides a comprehensive overview of Maven 3 including lifecycles and a detail of the default lifecycle and the associated phases within.
Welcome to presentation on Spring boot which is really great and relatively a new project from Spring.io. Its aim is to simplify creating new spring framework based projects and unify their configurations by applying some conventions. This convention over configuration is already successfully applied in so called modern web based frameworks like Grails, Django, Play framework, Rails etc.
JOHN HUMPHREYS VP OF ENGINEERING INFRASTRUCTURE SYSTEMS, NOMURA
Spring Boot is a modern and extensible development framework that aims (and succeeds!) to take as much pain as possible out of developing with Java. With just a few Maven dependencies, new or existing programs become runnable, init.d-compliant uber-JARs or uber-WARs with embedded web-servers and virtually zero-configuration, code or otherwise. As an added freebie, Spring Boot Actuator will provide your programs with amazing configuration-free production monitoring facilities that let you have RESTFUL endpoints serving live stack-traces, heap and GC statistics, database statuses, spring-bean definitions, and password-masked configuration file audits.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
This presentation is about Spring MVC. Topics covered in this session are:
1. HTTP Servlet
2. What is Spring MVC?
3. MVC Architecture
4. Request Processing Workflow in Spring MVC
5. Spring Web Application Context
6. Spring MVC Configuration
7. Important Annotations
This presentation provides a comprehensive overview of Maven 3 including lifecycles and a detail of the default lifecycle and the associated phases within.
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
We will dive into the basics of Inversion of Control (IOC) and Dependency Injection (DI) to review different ways of achieving decoupling, using and exploring both: Best Practices, Design and Anti Patterns. This presentation requires knowledge and understanding of basics like DRY, SoC, SRP, SOLID etc. which are building the base for decoupled architecture. However, we will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2015-06-25 Bay.NET South Bay, Mountain View, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
This session compares the Spring and Java EE stacks in terms of Web frameworks. It re-examines the motivations behind the Spring framework and explores the emergence of the Java EE programming model to meet the challenges posed. The presentation provides insight into when Spring and/or Java EE is appropriate for a building Web applications and if they can coexist.
Session 43 - Spring - Part 1 - IoC DI BeansPawanMM
In this session you will learn:
1.Spring Framework
2. Core Container
3. Data Access/Integration
4. Web Layer
5. Spring Setup
6. Key features
7. Spring Bean
8. Dependency Injection
9. Relation between DI and IoC
10. Spring IoC Containers
11. Spring DI
TUTORIAL-INTRODUCTION TO SPRING FOR BEGINNERS
EXPLANATION TO-Java Framework,Advantages of using SPRING,Difference between Hibernate and Spring.Spring architecture,Spring IoC Containters,Bean scope & Method Injection,Spring Inheritance.
Introduction to J2EE framework . Gives the primary knowledge about the framework involves in J2EE based web development . This is like Struts , Hibernate , spring ,JSF etc.
Enhance your career with spring framework Online training which helps you in mastering the real-world web applications with spring. Enroll in this course to get spring certified.
Some of the common interview questions asked during a Java Interview. These may apply to Java Interviews. Be prepared with answers for the interview questions below when you prepare for an interview. Also have an example to explain how you worked on various interview questions asked below. Java Developers are expected to have references and be able to explain from their past experiences. All the Best for a successful career as a Java Developer!
Some of the common interview questions asked during a Java Interview. These may apply to Java Interviews. Be prepared with answers for the interview questions below when you prepare for an interview. Also have an example to explain how you worked on various interview questions asked below. Java Developers are expected to have references and be able to explain from their past experiences. All the Best for a successful career as a Java Developer!
"Learn All Aspects Of Java Spring Framework step by step, Enhance your skills & Launch Your Career, On-Demand Course affordable price & classes on virtually every topic.Try Before You Buy
for java spring online training visit: https://goo.gl/P15Dbn"
Frameworks are large prewritten code to which you add your own code to solve a problem in a specific domain.
You make use of a framework by calling its methods,inheritance,and supplying “call-backs” listeners.
Spring is the most popular application development framework for enterprise Java™.
Millions of developers use Spring to create high performing, easily testable, reusable code without any lock-in.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
2. Know your trainer
Name: Arjun
Phone : +91 9691053479
Email: thakurarjun247@gmail.com
Freelance corporate trainer.
More than 2 years of strong hands-on experience in top MNCs in Java
and related technologies.
More than 2 years of experience as a Java trainer.
Clients / Previous Employers:
2
3. Agenda
Topics to be covered are:
Introduction to Spring framework
Benefits of Spring framework
Spring framework architecture
Inversion of Control (IoC)
Dependency Injection (DI)
3
4. Spring Framework
Light-weight comprehensive framework for building Java SE and
Java EE applications
Created by Rod Johnson
JavaBeans-based configuration management, applying Inversionof-Control principles, specifically using the Dependency Injection
technique
• Reduce dependencies of components on specific
implmentation of other components.
• A core bean factory, which is usable globally
Generic abstraction layer for database transaction management
4
5. Key Features
Built-in generic strategies for JTA and a single JDBC DataSource
This removes the dependency on a Java EE environment for
transaction support.
Integration with persistence frameworks Hibernate, JDO and
iBATIS.
MVC web application framework, built on core Spring functionality,
supporting many technologies for generating views, including JSP.
Extensive aspect-oriented programming (AOP) framework to
provide
services such as transaction management.
As with the Inversion-of-Control parts of the system, this aims to
improve the modularity of systems created using the framework.
5
6. Using Spring
Wiring of components through Dependency Injection
Promotes de-coupling among the parts that make the
application
Test-Driven Development (TDD)
POJO classes can be tested without being tied up with
the framework
Declarative programming through AOP
Easily configured aspects, esp. transaction support
Integration with other technologies
EJB for J2EE
Hibernate, iBatis, JDBC (for data access)
Velocity (for presentation)
Struts and WebWork (For web)
6
8. Core Package
The fundamental part which provides the IoC and Dependency
Injection features
BeanFactory, provides a sophisticated implementation of the
factory pattern
Removes the need for programmatic singletons
Decouple the configuration and specification of dependencies in
program logic.
8
9. Context Package
Provides a way to access objects in a framework-style
Inherits its features from the beans package and adds support for
• internationalization (I18N)
• event-propagation
• resource-loading
• transparent creation of contexts by
9
10. DAO Package
Provides a JDBC-abstraction layer that removes the need to do
tedious
JDBC coding and parsing of database-vendor specific error codes
Programmatic as well as declarative transaction management for
• classes implementing special interfaces
• POJOs
10
11. ORM Package
The ORM package provides integration layers for popular objectrelational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
Using the ORM package you can use all those O/R-mappers in
combination with all the other features Spring offers, such as the
simple declarative transaction management feature mentioned
previously
11
12. AOP Package
Spring's AOP package provides an AOP Alliance-compliant aspectoriented programming implementation
• method-interceptors and pointcuts to cleanly decouple code
implementing functionality that should logically speaking be
separated
Using source-level metadata functionality you can also incorporate all
kinds of behavioral information into your code
12
13. MVC Package
Web package provides features, such as
• multipart file-upload functionality,
• the initialization of the IoC container using servlet listeners
• A web-oriented application context.
• Can be used together with WebWork or Struts,
Spring's MVC package provides a Model-View-Controller (MVC)
implementation for web applications
Provides a clean separation between domain model code and web
forms, and allows all the other features of the Spring Framework.
13
15. Inversion of Control
The Spring IoC container makes use of Java POJO classes and
configuration metadata.
It produces a fully configured and executable system or application.
15
16. Introduction to IoC
Traditional software is developed with the application code “in
control”
• The application defines the “main”function/method/entry point
• Calls the application’s components to perform processing
Frameworks invert this relationship and call the application code
• “Don’t call us we’ll call you”
• Framework provides the “main”function/method/entry point
• Application code fits into the framework and is called when the
framework decides.
A particular variant of IoC is “dependency injection”
16
17. Dependency Injection
Most frameworks use the “Service Lookup” approach to allow
application code to find its dependencies.
• e.g. J2EE code looks up resources via JNDI
• CORBA applications find services via a Naming Service
• The lookup mechanism is hard coded into the application code
Dependency Injection frameworks supply the resources that a
component needs when initialising it
• Component declares resources required (usually as interface
types)
• Framework configuration defines concrete instances to use
• Framework passes component the concrete resources at load
time
“IoC containers” are “Dependency Injection” containers
17
19. IoC Container
The org.springframework.beans and org.springframework.context
packages provide the basis for the Spring Framework's IoC container.
BeanFactory interface
provides an advanced configuration mechanism capable of managing
objects of any nature.
ApplicationContext interface , a sub interface of BeanFactory is used
for
• Easier integration with Spring's AOP features,
• Message resource handling (in internationalization),
• Event propagation
• Specific contexts such as the WebApplicationContext
19
20. Container and Beans
A bean is simply an object that is instantiated, assembled and
otherwise managed by a Spring IoC container
The beans, and the dependencies between them, are reflected in
the configuration metadata used by a container.
org.springframework.beans.factory.BeanFactory is the representation
of the Spring IoC container, it’s responsible for:
• containing and managing beans,
• instantiating or sourcing application objects
• configuring such objects
• assembling the dependencies between objects.
20
21. The Container
There are a number of implementations of the BeanFactory interface
The most commonly used BeanFactory implementation is the
XmlBeanFactory class.
The XmlBeanFactory takes the XML configuration metadata and uses
it to create a fully configured system or application.
21
22. Configuration Meta Data
The meta-data informs the Spring container as to how to “instantiate,
configure, and assemble *the objects in your application+”.
XML-based metadata is the most commonly used form of
configuration metadata.
Configuration consists of at least one bean definition that the
container must manage, but could be more than one bean definition.
When using XML-based configuration metadata, these beans are
configured as <bean/> elements inside a top-level <beans/> element.
22
23. Simple XML Configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans2.5.xsd">
<bean id="..." class="...">
<!--collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!--collaborators and configuration for this bean go here -->
</bean>
<!--more bean definitions go here -->
</beans>
23
24. Instantiating a Container
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"services.xml", "daos.xml"});
// an ApplicationContext is also a BeanFactory (via inheritance)
BeanFactory factory = context;
24
25. The Bean
The container manages the beans , and they are are created using
the configuration metadata.
Bean definitions are represented as BeanDefinition objects, which
contain the following metadata:
package-qualified class name: typically this is the actual
implementation class of the bean being defined.
bean behavioral configuration elements,
• which state how the bean should behave in the container (scope,
lifecycle callbacks etc.,).
references to other beans
• which are needed for the bean to do its work; these references
are also called collaborators or dependencies.
other configuration settings
• An example would be the number of connections to use in a
bean that manages a connection pool, or the size limit of the
pool.
25
26. Benefits of Dependency Injection
Flexible
• Avoid adding lookup code in business logic
Testable
• No need to depend on external resources or containers for
testing
Maintainable
• Promotes a consistent approach across all applications and
teams
• Allows reuse in different application environments by changing
configuration files instead of code
26
27. Dependency Injection
BeanFactory interface
XmlBeanFactory implementation
Bean configuration file
Constructor dependency Injection
• Dependencies are provided through the constructors of the
component
Setter dependency injection
• Dependencies are provided through the JavaBeanstyle setter
methods of the component
• More popular than Constructor dependency injection
Beans
Injection Parameters
27
28. BeanFactory Class
BeanFactory object is responsible for managing beans and their
dependencies
Your application interacts with Spring's DI container through
BeanFactory interface
• BeanFactory object has to be created by the application typically
XmlBeanFactory
• BeanFactory object, when it gets created, read bean
configuration file and performs the wiring
• Once created, the application can access the beans via
BeanFactory interface
XmlBeanFactory
• Convenience extension of DefaultListableBeanFactory that reads
bean definitions from an XML document
28
29. Beans
The term “bean” is used to refer any component managed by the
BeanFactory
The “beans” are in the form of JavaBeans (in most cases)
• no arg constructor
• getter and setter methods for the properties
Beans are singletons by default
Properties
• the beans may be simple values or references to other beans
29
30. The Bean – A Java Class
public class Example {
private int empid;
private String empname;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Example() {super();}} // no arg constructor
30
31. Injecting Simple Values–XML File
Each bean is defined using <bean> tag under the root of the <beans>
tag
The id attribute is used to give the bean its default name
The class attribute specifies the type of the bean
<bean id="firstBean" class="com.training.Example">
<property name="empname">
<value>ramesh</value>
</property>
<property name="empid"><value>100</value></property>
</bean>
</beans>
31
32. Injecting Simple Values–XML File
Each bean is defined using <bean> tag under the root of the <beans>
tag
The id attribute is used to give the bean its default name
The class attribute specifies the type of the bean
<bean id="firstBean" class="com.training.Example">
<property name="empname">
<value>ramesh</value>
</property>
<property name="empid"><value>100</value></property>
</bean>
</beans>
32
33. Spring Application
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class TestExample {
public static void main(String[] args) {
BeanFactory bfact = new XmlBeanFactory(new
FileSystemResource("mybean.xml"));
Example exObj = (Example)bfact.getBean("firstBean");
System.out.println(exObj.getEmpid());
System.out.println(exObj.getEmpname());
}
}
33
34. Injection Parameter Types
Spring supports various kinds of injection parameters
• Simple values
• Beans in the same factory
• Beans in another factory
• Collections
• Externally defined properties
You can use these types for both setter or constructor injections
34
35. Injecting Bean into the same Factory
Used when you need to inject one bean into another (target bean)
Configure both beans first
Configure an injection using <ref> tag in the target bean's <property>
or <constructor-arg>
The type being injected does not have to be the exact type defined
on the target
if the type defined on the target is an interface, the type being
injected must be an implementation of it
if the type defined on the target is a class, the type being injected can
be the same type or sub-type
35
36. Constructor Injection
All dependencies injected via constructor arguments
– Requires potentially complex constructor argument lists
Avoids reliance on get/set naming conventions
– e.g. addStateObserver()
Less flexible initialisation
– Need a constructor per configuration option
Can be difficult to understand
– Rely on ordering of parameters
36
37. Constructor Dependency Injection
(code snippet)
public class Invoice {
private Items item;
private String customer;
private double amount;
public Invoice(Items item)
{
this.item = item;
}
public Invoice()
{
super();
}
// Set/Get Methods
}
public class Items {
private int itemno;
private String itemname;
public Items() {
super();
}
// Set/Get Methods
}
37
38. Constructor Dependency Injection
(code snippet)
public class TestConstDepend {
public static void main(String[] args) {
BeanFactory bf = new XmlBeanFactory(new
FileSystemResource("mybeandef.xml"));
Invoice inv = (Invoice)bf.getBean("Invoice");
System.out.println(inv.getItem());
System.out.println(inv.getCustomer());
System.out.println(inv.getAmount());
}
}
38
39. Setter Injection
All dependencies injected via setter methods
– No need for constructors
Allows flexible initialisation
– Any set of properties can be initialised
Named properties allow for readable configuration data
– Clear what is being injected
Requires JavaBean conventions to be followed
– Non standard method names are problematic
Can result in invalid object configurations
– Need post initialisation checking methods
39
40. Setter Injection (code snippet)
public class Policy {
private int policyCode;
private String policyName;
public Policy(int policyCode,
String policyName) {
this.policyCode =
policyCode;
this.policyName =
policyName;
}
public Policy() {
super();
}
//SET-GET Methods
}
public class Insurance {
private int policynumber;
private Policy policyData;
public Policy getPolicyData() {
return policyData;
}
public void
setPolicyData(Policy
policyData) {
this.policyData =
policyData;
}
//SET-GET Methods
}
40
41. Setter Injection (code snippet)
public class TestSetterDependcy {
public static void main(String[] args) {
BeanFactory beanFact = new XmlBeanFactory
(new FileSystemResource("myBean.xml"));
Insurance ins =(Insurance)beanFact.getBean("Insurance");
System.out.println("Policy Number"+ins.getPolicynumber());
System.out.println("Policy Code“ +
ins.getPolicyData().getPolicyCode());
System.out.println("Policy Holder Name"+
ins.getPolicyData().getPolicyName());
}
}
41