0% found this document useful (0 votes)
16 views34 pages

Day 10-Injecting Data, Autowiring, Bean Concepts

Injecting data, Autowiring, Bean Concepts

Uploaded by

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

Day 10-Injecting Data, Autowiring, Bean Concepts

Injecting data, Autowiring, Bean Concepts

Uploaded by

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

Deloitte

Training
2016

FOUNDATION TRAINING
Injecting data, Autowiring,
Bean Concepts
1
Deloitte Training 2016

J2EE
Day 10

3
Objectives of Day 10 Deloitte Training 2016

At the end of this module, you will be able to:


• Conduct programming using Spring
• Understand autowiring concept

4
Spring Dependency Injection
 Inversion of Control (IoC)
 “Hollywood Principle”
Don't call me, I'll call you
 “Container” resolves (injects) dependencies of
components by setting implementation object (push)
 As opposed to component instantiating or Service
Locator pattern where component locates
implementation (pull), Martin Fowler calls
Dependency Injection
Dependency Injection Variants
 Variations on dependency injection
 Interface based (Avalon)

 Constructor-based (PicoContainer, Spring)

 Setter-based (Spring)

 BeanFactory provides configuration framework to


initialize and “wire” JavaBeans
 org.springframework.beans and
org.springframework.context
 Typically use the XmlBeanFactory, employing XML
configuration files
What is a bean?
 Typical java bean with a unique id
 In spring there are basically two types
 Singleton
One instance of the bean created and referenced
each time it is requested
 Prototype (non-singleton)
New bean created each time
Same as new ClassName()
 Beans are normally created by Spring as late as
possible

7
What is a bean definition?
 Defines a bean for Spring to manage
Key attributes
 class (required): fully qualified java class name
 id: the unique identifier for this bean
configuration: (singleton, init-method, etc.)
 constructor-arg: arguments to pass to the
constructor at creation time
 property: arguments to pass to the bean setters at
creation time
 Collaborators: other beans needed in this bean
(a.k.a dependencies), specified in property or
constructor-arg
 Typically defined in an XML file
8
Sample bean definition

<bean id="exampleBean" class=”org.example.ExampleBean">


<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty"><value>1</value></property>
</bean>

public class ExampleBean {


private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne; }
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo; }
public void setIntegerProperty(int i) {
this.i = i; }

}
9
What is a bean factory?

• Often seen as an ApplicationContext


– BeanFactory is not used directly often
– ApplicationContext is a complete superset of bean factory
methods
• Same interface implemented
• Offers a richer set of features
• Spring uses a BeanFactory to create, manage and
locate “beans” which are basically instances of a
class
– Typical usage is an XML bean factory which allows
configuration via XML files
10
How are beans created?
• Beans are created in order based on the dependency graph
– Often they are created when the factory loads the definitions
– Can override this behavior in bean
<bean class=“className” lazy-init=“true” />
– You can also override this in the factory or context but this is not
recommended
• Spring will instantiate beans in the order required by their
dependencies
1. app scope singleton - eagerly instantiated at container startup
2. lazy dependency - created when dependent bean created
3. VERY lazy dependency - created when accessed in code

11
How are beans injected?
• A dependency graph is constructed based on
the various bean definitions
• Beans are created using constructors (mostly
no-arg) or factory methods
• Dependencies that were not injected via
constructor are then injected using setters
• Any dependency that has not been created is
created as needed

12
Multiple bean config files
• There are 3 ways to load multiple bean config files (allows
for logical division of beans)
– Load multiple config files from web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/WEB-INF/spring-config.xml, classpath:/WEB-
INF/applicationContext.xml</param-value>
</context-param>

– Use the import tag


<import resource="services.xml"/>
– Load multiple config files using Resources in the
application context constructor
• Recommended by the spring team
• Not always possible though
ClassPathXmlApplicationContext appContext = new
ClassPathXmlApplicationContext( new String[]
{"applicationContext.xml", "applicationContext-
part2.xml"});
13
Bean properties?
• The primary method of dependency injection
• Can be another bean, value, collection, etc.
<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean">
<ref bean="someOtherBean" />
</property>
</bean>

• This can be written in shorthand as follows


<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>

14
Anonymous vs ID
• Beans that do not need to be referenced
elsewhere can be defined anonymously
• This bean is identified (has an id) and can be
accessed to inject it into another bean
<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>

• This bean is anonymous (no id)


<bean class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>

15
What is an inner bean?
<bean id="outer" class="org.example.SomeBean">
<property name="person">
<bean class="org.example.PersonImpl">
<property name="name"><value>Aaron</value></property>
<property name="age"><value>31</value></property>
</bean>
</property>
</bean>

• It is a way to define a bean needed by


another bean in a shorthand way
– Always anonymous (id is ignored)
– Always prototype (non-singleton)

16
Bean init-method
• The init method runs AFTER all bean
dependencies are loaded
– Constructor loads when the bean is first instantiated
– Allows the programmer to execute code once all
dependencies are present

<bean id="exampleBean" class=”org.example.ExampleBean"


init-method=”init” />

public class ExampleBean {


public void init() {
// do something
}
}

17
Bean values
• Spring can inject more than just other beans
• Values on beans can be of a few types
– Direct value (string, int, etc.)
– Collection (list, set, map, props)
– Bean
– Compound property

Example of injecting a string value

<bean class="org.example.ExampleBean">
<property name="email">
<value>[email protected]</value>
</property>
</bean>
18
Abstract (parent) beans
• Allows definition of part of a bean which can be
reused many times in other bean definitions

<bean id="abstractBean" abstract="true" The parent bean defines 2


class="org.example.ParentBean"> values (name, age)
<property name="name" value="parent-AZ"/> The child bean uses the
<property name="age" value="31"/> parent age value (31)
</bean> The child bean overrides
the parent name value
<bean id="childBean" (from parent-AZ to child-
class="org.example.ChildBean" AZ)
parent="abstractBean" init-method="init"> Parent bean could not be
<property name="name" value="child-AZ"/> injected, child could
</bean>

19
Dependency Injection (cont'd)
• BeanFactory configured components need
have no Spring dependencies
– Simple JavaBeans
• Beans are singletons by default
• Properties may be simple values or
references to other beans
• Built-in support for defining Lists, Maps,
Sets, and Properties collection types.
– Custom PropertyEditors may be defined to
convert string values to other, arbitrary types.
XmlBeanFactory Example
• Property and constructor based IoC
<bean id="exampleBean" class="examples.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty">1</property>
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>


<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

<bean id="exampleBean" class="examples.ExampleBean">


<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg><value>1</value></constructor-arg>
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>


<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Bean Creation
• Direct instantiation
– <bean id=“beanId” class=“className”>
• BeanFactory instantiation
– Same syntax but class is subclass of BeanFactory
– getObject() called to obtain Bean
• Static Factory
– <bean id=“beanId” class=“className" factory-method="
staticCreationMethod“>
• Instance Factory Method
– <bean id=“beanId” factory-bean=“existingBeanId" factory-
method=“nonStaticCreationMethod">
Bean Creation
• Beans may be singletons or “prototypes”
– Attribute singleton=“false” causes instantiation
with each getBean() lookup
– Singleton is default
• XmlBeanFactory pre-instantiates singletons
– May be overridden on per-instance basis by lazy-
init=“true”
• Beans may also be marked abstract, allowing
reuse of attribute values through inheritance
Autowiring Properties
• Beans may be auto-wired (rather than using <ref>)
– Per-bean attribute autowire
– Explicit settings override
• autowire=“name”
– Bean identifier matches property name
• autowire=“type”
– Type matches other defined bean
• autowire=”constructor”
– Match constructor argument types
• autowire=”autodetect”
– Attempt by constructor, otherwise “type”
Dependency Checking
• Ensures properties are defined
– Per-bean attribute dependency-check
– None required by default
– Verifies autowiring succeeded
• “simple”
– all but collaborators
• “object”
– collaborators only
• “all”
– Collaborators, primitive types, and collections
Lifecycle Customization
• Can define init method called after properties
set
– init-method=”<method-name>”
• Can define destroy method as shutdown hook
– destroy-method=”<method-name>”
• May alternatively implement InitializingBean
and/or DisposableBean
– At cost of Spring dependency
BeanFactory Miscellany
• BeanFactoryAware interface provides BeanFactory for
bean
– setBeanFactory(BeanFactory)
• BeanNameAware interface provides bean name
– setBeanName(String)
• FactoryBean for beans which are themselves factories
– Object getObject()
– Boolean isSingleton()
– Class getObjectType()
BeanFactory Usage

InputStream is = new FileInputStream("beans.xml");


XmlBeanFactory factory = new XmlBeanFactory(is);
MyBeanClass bean = (MyBeanClass)factory.getBean(“myBean”);

OR
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”);
ApplicationContext
• Extends functionality of BeanFactory
• Pre-instantiates singleton beans
• Detects and registers BeanPostProcessors and
BeanFactoryPostProcessors
• Supports nesting of contexts
• ApplicationListener and ApplicationEvents
– Initialized and closed predefined
– Custom may be created
• MessageSource provides i18n messaging
– <bean id=”messageSource”
class=”...ResourceBundleMessageSource”/>
– Contains list of bundle base names
Web Initialization
• Web applications may use
ContextLoaderListener to initialize Spring
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml
</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Automatically done by Spring DispatcherServlet


Specialized Beans
• MethodInvokingFactoryBean
– Invokes method on registered beans or any
static methods
– Stores return value
• SingletonBeanFactoryLocator and
ContextSingletonBeanFactoryLocator
– Useful for sharing BeanFactories
– Eliminate duplication of beans in multiple similar
factories or contexts
ApplicationContext customization
• Defined beans inheriting from BeanFactoryPostProcessor
are detected and invoked
• CustomEditorConfigurer
– Registers custom PropertyEditors for converting
configuration string values to specific types
• AutoProxyCreators
– Wrap beans in proxies based on various criteria (name,
metadata, etc)
• PropertyResourceConfigurer
• Sets from property file and/or system properties
ApplicationContext Example

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>database.properties</value></property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${database.connection.driver_class}</value>
</property>
<property name="url">
<value>${database.connection.url}</value>
</property>
</bean>
Summary Deloitte Training 2016
You have learned how to:

• To use and apply Reflection API


• Use Maven tool
• Enhanced utilities of Eclipse

34

You might also like