Public Static Factory Method To Create Spring Beans

Besides factory bean, you can also use a factory method to create spring bean, but the factory method must be public static and return the desired spring bean class type. This article will show you examples of how to do that.

This example has two classes, one is DBConnectionDTO which store JDBC connection information for a database, the other is DBConnectionFactory which has a public static factory method that returns an instance of DBConnectionDTO with provided database connection parameters.

1.DBConnectionDTO.java.

This is the class that will be returned by the factory method.

public class DBConnectionDTO {
	
	private String connUrl;
	
	private String jdbcDriverClass;
	
	private String dbUserName;
	
	private String dbPassword;

	public String getConnUrl() {
		return connUrl;
	}

	public void setConnUrl(String connUrl) {
		this.connUrl = connUrl;
	}

	public String getJdbcDriverClass() {
		return jdbcDriverClass;
	}

	public void setJdbcDriverClass(String jdbcDriverClass) {
		this.jdbcDriverClass = jdbcDriverClass;
	}

	public String getDbUserName() {
		return dbUserName;
	}

	public void setDbUserName(String dbUserName) {
		this.dbUserName = dbUserName;
	}

	public String getDbPassword() {
		return dbPassword;
	}

	public void setDbPassword(String dbPassword) {
		this.dbPassword = dbPassword;
	}

	@Override
	public String toString() {
		StringBuffer retBuf = new StringBuffer();
		
		retBuf.append("Jdbc driver class : " + this.getJdbcDriverClass());
		retBuf.append(" , Connection url : " + this.getConnUrl());
		retBuf.append(" , DB username : " + this.getDbUserName());
		retBuf.append(" , DB password : " + this.getDbPassword());
		
		return retBuf.toString();
	}
}

2. DBConnectionFactory.java.

This is the class that has a public static factory method, this method will return an instance of DBConnectionDTO class with input parameters.

public class DBConnectionFactory {

	/* This is the factory method, it return DBConnectionDTO object with provided input parameters. */
	public static DBConnectionDTO createDBConnectionDto(String jdbcDriverClass, String connUrl, String dbUserName, String dbPassword)
	{
		DBConnectionDTO ret = new DBConnectionDTO();
		
		if(!DBConnectionFactory.ifStringEmpty(jdbcDriverClass) && !DBConnectionFactory.ifStringEmpty(connUrl) && !DBConnectionFactory.ifStringEmpty(dbUserName))
		{
			ret.setJdbcDriverClass(jdbcDriverClass);
			
			ret.setConnUrl(connUrl);
			
			ret.setDbUserName(dbUserName);
			
			ret.setDbPassword(dbPassword);
		}else
		{
			throw new IllegalArgumentException("Database connection parameters can not be empty. ");
		}
		
		return ret;
	}

	/* This is a util method to check whether the input string is empty or not.*/
	private static boolean ifStringEmpty(String str)
	{
		if(str!=null && str.trim().length()>0)
		{
			return false;
		}else
		{
			return true;
		}
	}
	
	/* This is the main method which will load the spring application context 
	 * and get related spring bean by bean id. 
	 * 
	 * Because the spring bean configuration xml has an attribute named factory-method, 
	 * then spring will execute the specified factory-method(createDBConnectionDto) in this class 
	 * and return an instance of DBConnectionDTO class by that method. */
	public static void main(String[] args) {
		
	   	// Initiate Spring application context, this line code will invoke bean initialize method.
		ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml");

		// Get the mysql db connection object.
		DBConnectionDTO dbConnMysql = (DBConnectionDTO)springAppContext.getBean("mysqlDBConn");
		System.out.println(dbConnMysql.toString());
		
		// Get the oracle db connection object.
		DBConnectionDTO dbConnOracle = (DBConnectionDTO)springAppContext.getBean("oracleDBConn");
		System.out.println(dbConnOracle.toString());
	}
}

3. BeanSettings.xml.

This is the spring application context configuration XML which declares two database connection beans. Each spring bean is generated by the factory method DBConnectionFactory.createDBConnectionDto with input parameters. The first spring bean can be used to connect to the oracle database, and the second spring bean can be used to connect to the MySQL database.

<bean id="oracleDBConn" class="com.dev2qa.example.spring.bean.factorymethod.DBConnectionFactory" 
      factory-method="createDBConnectionDto">    
      <constructor-arg index="0" value="oracle.jdbc.driver.OracleDriver"/>    
      <constructor-arg index="1" value="jdbc:oracle:thin:@localhost:1521:DataTiger"/>    
      <constructor-arg index="2" value="system"/>    
      <constructor-arg index="3" value="manager"/> 
</bean> 

<bean id="mysqlDBConn" class="com.dev2qa.example.spring.bean.factorymethod.DBConnectionFactory" 
      factory-method="createDBConnectionDto">    
      <constructor-arg index="0" value="com.mysql.jdbc.Driver"/>    
      <constructor-arg index="1" value="jdbc:mysql://localhost:3306/test"/>    
      <constructor-arg index="2" value="root"/>    
      <constructor-arg index="3" value=""/> 
</bean>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.