Spring Bean

Spring Bean is a normal pojo Java class with setter and getter methods which get initialized by Spring Container. It gets call as Spring bean if it is initialized by Spring container.

On high level Spring bean is all about three things.

1. definition

2. scopes

3. life cycle.

Spring bean metadata can be configured using below methods:

1. XML based configuration

2. Annotation based configuration

3. Java based configuration.

In this blog we will talk about first option XML based configuration.
 

There are multiple attributes which are defined for <bean> tag:

class

This attribute will be looking for complete class name with package.

id

This will help us to create an instance of a class, similar to new keyword in Java. It is also called as bean identifier

name

This will work as an instance name defined with new keyword in Java or also called as bean identifier. name helps us to create an alias for bean class.

scope

This will define the scope of object. Spring supports singleton, prototype, request, session and global-session as a scope.

constructor-arg

This will be use to inject the dependency using constructor arguments.

autowire


This will be use for dependency injection.
There are four types of auto wiring mode as no, byName, byType, constructor

no → This is Spring’s default, also called as No automagical wiring. ref tag element uses to define bean references in xml file. autowire=default is equivalent to autowire=no

byName → Properties of the autowired bean will be wired by searching for bean with same name/id in the configuration file. If such a bean is found it is injected, properties for which no matching bean is found will remain unwired which may later result in error.

byType → It will look for bean having compatible property’s type.

constructor → Wiring will be done one the basis of constructor. It will look for the bean with matching constructor argument.

init-method

This will call custom method will get invoke just after setting bean properties. The method must have no arguments, but may throw any exception.

destroy-method

This will call custom destroy method defined having no arguments. This function can throw an exception.

lazy-init

It is used for IoC container to create a bean instance when it is first requested, rather than at the startup of the application or on load of config file.

Note: We have multiple inline examples for all above attributes. 

Below are some of the example to define bean attribute in bean.xml 

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan