Declare bean in Spring container
The following JARs have to be included 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
- external libraries
commons.logging-1.1.1.jar
package com.javacodegeeks.snippets.enterprise;
public class HelloBean {
public void printHello() {
System.out.println("Hello World!");
}
}
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();
}
}
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>
Output:
Hello World!
