BeanFactory

The BeanFactory container acts as the simplest container providing basic support for DI, and it is defined by the org.springframework.beans.factory.BeanFactory interface. BeanFactory is responsible to source, configure, and assemble the dependencies between objects. BeanFactory mainly acts as an object pool, where object creation and destruction is managed through configuration. The most popular and useful implementation of BeanFactory is the org.springframework.context.support.ClassPathXmlApplicationContext. The ClassPathXmlApplicationContext uses XML configuration metadata to create a fully configured application. 

The following sample defines a simple HelloWorld application using ClassPathXmlApplicationContext. The content of Beans.xml looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="bankAccount"
class="com.packt.springhighperformance.ch1.bankingapp.BankAccount">
<property name="accountType" value="Savings Bank Account" />
</bean>
</beans>

The preceding XML code represents the content of bean XML configuration. It has a single bean configured, which has a single property with the name message. It has a default value set for the property.

Now, the following Java class represents bean configured in the preceding XML.

Let's have a look at HelloWorld.java:

package com.packt.springhighperformance.ch1.bankingapp;

public class BankAccount {
private String accountType;

public void setAccountType(String accountType) {
this.accountType = accountType;
}

public String getAccountType() {
return this.accountType;
}
}

At the end, we need to use ClassPathXmlApplicationContext to create the HelloWorld bean and invoke a method in the created Spring bean.

Main.java looks as follows:

package com.packt.springhighperformance.ch1.bankingapp;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.
support.ClassPathXmlApplicationContext;

public class Main {

private static final Logger LOGGER = Logger.getLogger(Main.class);

@SuppressWarnings("resource")
public static void main(String[] args) {
BeanFactory beanFactory = new
ClassPathXmlApplicationContext("Beans.xml");
BankAccount obj = (BankAccount) beanFactory.getBean("bankAccount");
LOGGER.info(obj.getAccountType());
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset