What is a Spring Bean?

What is a Spring Bean?

A “Spring Bean” is simply a Java object.

When Java objects are created by the Spring Container, then Spring refers to them as “Spring Beans”.

Spring Beans are created from normal Java classes just like Java objects.

Two ways of creating Spring Beans:

1. By using an xml file:

<bean id="someBean" class="com.package.bean">
    <property name="dependency" ref="someOtherRefBeanId"/>
</bean>

2. By using java code:

@Configuration
public abstract class VisibilityConfiguration {

  @Bean
  public Bean publicBean() {
     Bean bean = new Bean();
     bean.setDependency(hiddenBean());
     return bean;
  }

  @Bean
  private HiddenBean hiddenBean() {
     return new Bean("private bean");
  }
}

 

Conclusion:

Both ways can be used and it’s up to developers to choose which one suits better for their apps. However, the modern way is to use Java code.

Share This:

Related Posts