Declare bean in Spring container
With this example we are going to demonstrate how to declare a Bean in the Spring container. A Spring bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. In short, to declare a Class as a simple Spring Bean you should follow the steps below:
1. Include the following JARs in the classpath:
- – Spring framework libraries
- org.springframework.asm-3.0.2.RELEASE.jar
- org.springframework.beans-3.0.2.RELEASE.jar org.springframework.context-3.0.2.RELEASE.jar
- org.springframework.core-3.0.2.RELEASE.jar
- org.springframework.expression-3.0.2.RELEASE.jar
- commons.logging-1.1.1.jar
– external libraries
2. Create a simple Java class
The class HelloBean.java
has a simple method, printHello()
.
package com.javacodegeeks.snippets.enterprise; public class HelloBean { public void printHello() { System.out.println("Hello World!"); } }
3. Define the HelloBean.java class as a Spring bean, in Spring configuration file.
The bean is defined in spring-beans.xml
file inside the <bean>
element. It has two attributes, the bean id
and the class
that is the class of the bean.
spring-beans.xml
<!--?xml version="1.0" encoding="UTF-8"?--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="helloBean" class="com.javacodegeeks.snippets.enterprise.HelloBean" /> </beans>
3. Run the application
In DeclareBeanInSpringContainer.java
class we load the Spring configuration file, using the FileSystemXmlApplicationContext
Class with the configuration file name. Using the getBean(String name)
API method of ApplicationContext
Class, we can get an instance of the helloBean
and invoke its method.
package com.javacodegeeks.snippets.enterprise; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class DeclareBeanInSpringContainer { public static void main(String[] args) throws Exception { ApplicationContext context = new FileSystemXmlApplicationContext("spring-beans.xml"); HelloBean helloBean = (HelloBean) context.getBean("helloBean"); helloBean.printHello(); } }
4. Output
The output is shown below:
Output:
Hello World!
This was an example of how to declare a Bean in the Spring container.