Monday, February 12, 2018

Bean and Bean definition

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()


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

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

}

No comments:

Post a Comment