What is a bean in Spring ?
- Typical java bean with a unique id
- Typically defined in an XML file
- 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
Example:
<bean id="exampleBean" class=”org.example.ExampleBean">
<property
name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<ref bean="anotherExampleBean"/>
</property>
<property
name="beanTwo">
<ref bean="yetAnotherBean"/>
</property>
<ref bean="yetAnotherBean"/>
</property>
<property
name="integerProperty">
<value>1</value>
</property>
<value>1</value>
</property>
</bean>
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
Posted in: