Tuesday, February 13, 2018

bean factory, Bean Injection,

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


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
app scope singleton - eagerly instantiated at container startup
lazy dependency - created when dependent bean created
VERY lazy dependency - created when accessed in code

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

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"});

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>

No comments:

Post a Comment