Expert Spring MVC and Web Flow

(Dana P.) #1
Custom Valang function classes often need collaborating objects to do their work.
These objects can be autowired by name or by type. To get collaborating objects, add
JavaBean properties to the function class and overwrite either the isAutoWireByName()or
isAutoWireByType()methods defined in AbstractFunction. The init()method that’s also
defined in AbstractFunctioncan be overwritten to make sure mandatory properties have
been set.
The init()method will be called by Valang after the properties have been autowired.
Autowiring by type will fail if more than one bean definition of the same type is found in the
Spring container. See Listing 9-17.

Listing 9-17.Example of Autowiring in Custom Valang Functions

package com.apress.expertspringmvc.validation;

import org.springmodules.validation.functions.AbstractFunction;
import org.springmodules.validation.functions.Function;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

public class SqlQueryForIntFunction extends AbstractFunction {
private JdbcTemplate jdbcTemplate = null;

public SqlQueryForIntFunction(Function[] functions, int line, int column) {
super(functions, line, column);
defineMinNumberOfArguments(1);
defineMaxNumberOfArguments(2);
}

public boolean isAutowireByName() {
return true;
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
jdbcTemplate = jdbcTemplate;
}

public void init() throws Exception {
Assert.notNull(jdbcTemplate, "JdbcTemplate is required!");
}

protected Object doGetResult(Object target) {
String sql = getArguments()[0].getResult(target).toString();
return new Integer(jdbcTemplate.queryForInt(sql));
}
}

The SqlQueryForIntFunctiontakes a SQL statement that returns an integer value like a
count on a database table. The SQL statement is executed on an instance of JdbcTemplatethat

276 CHAPTER 9 ■VALIDATION

Free download pdf