"beanutils allike"를 사용하는 가장 간단한 방법은 대체합니다
-
02-07-2019 - |
문제
Pojo 매개 변수를 추출하기 위해 Beanutils에서 사용하는 것과 동일한 알려진 표기법을 사용할 수있는 라이브러리가 있습니까?
Beanutils 자체 또는 비슷한 기능을 가진 다른 라이브러리를 사용하여 내 자신을 굴릴 수 있다는 것을 알고 있지만 바퀴를 재창조하고 싶지 않았습니다.
다음과 같이 문자열을 가져 가고 싶습니다.
String s = "User ${user.name} just placed an order. Deliver is to be
made to ${user.address.street}, ${user.address.number} - ${user.address.city} /
${user.address.state}";
아래 사용자 수업의 한 인스턴스를 전달합니다.
public class User {
private String name;
private Address address;
// (...)
public String getName() { return name; }
public Address getAddress() { return address; }
}
public class Address {
private String street;
private int number;
private String city;
private String state;
public String getStreet() { return street; }
public int getNumber() { return number; }
// other getters...
}
다음과 같은 것입니다.
System.out.println(BeanUtilsReplacer.replaceString(s, user));
각 자리 표시자가 실제 값으로 교체하게됩니다.
어떤 아이디어?
해결책
Beanutils를 사용하여 자신을 굴리는 것은 너무 많은 휠 재창조를 소지하지 않습니다 (요청 한 것만 큼 기본적으로 원한다고 가정). 이 구현은 교체 컨텍스트에 대한 맵을 취합니다. 여기서 맵 키는 교체를 위해 주어진 가변 조회 경로의 첫 번째 부분에 해당해야합니다.
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsReplacer
{
private static Pattern lookupPattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
public static String replaceString(String input, Map<String, Object> context)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
int position = 0;
StringBuffer result = new StringBuffer();
Matcher m = lookupPattern.matcher(input);
while (m.find())
{
result.append(input.substring(position, m.start()));
result.append(BeanUtils.getNestedProperty(context, m.group(1)));
position = m.end();
}
if (position == 0)
{
return input;
}
else
{
result.append(input.substring(position));
return result.toString();
}
}
}
질문에 제공된 변수가 주어지면 :
Map<String, Object> context = new HashMap<String, Object>();
context.put("user", user);
System.out.println(BeanUtilsReplacer.replaceString(s, context));
다른 팁
이와 유사한 질문에 대한 답을 참조하십시오 독립형 컨텍스트에서 표현 언어를 사용합니다.
Spring Framework에는이를 수행하는 기능이 있어야합니다 (아래 Spring JDBC 예제 참조). Groovy를 사용할 수 있다면 (Groovy.jar 파일을 추가) Groovy의 GSTRING 기능을 사용하여이를 잘 수행 할 수 있습니다.
그루비 예
foxtype = 'quick'
foxcolor = ['b', 'r', 'o', 'w', 'n']
println "The $foxtype ${foxcolor.join()} fox"
Spring JDBC는 다음과 같은 콩의 이름이 지정된 이름 지정된 바인드 변수를 지원하는 데 사용하는 기능이 있습니다.
public int countOfActors(Actor exampleActor) {
// notice how the named parameters match the properties of the above 'Actor' class
String sql = "select count(0) from T_ACTOR where first_name = :firstName and last_name = :lastName";
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);
return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
}
문자열 예제는 Velocity 또는 Freemarker와 같은 몇 가지 템플릿 엔진의 유효한 템플릿입니다. 이 라이브러리는 템플릿을 일부 객체 (예 : 예 : 예 : 예 : 예 : 예 : 예 : 예 :)와 병합하는 방법을 제공합니다.
보다 http://velocity.apache.org/ 또는 http://www.freemarker.org/
일부 예제 코드 (프리 마커 사이트에서) :
/* ------------------------------------------------------------------- */
/* You usually do it only once in the whole application life-cycle: */
/* Create and adjust the configuration */
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(
new File("/where/you/store/templates"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
/* ------------------------------------------------------------------- */
/* You usually do these for many times in the application life-cycle: */
/* Get or create a template */
Template temp = cfg.getTemplate("test.ftl");
/* Create a data-model */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* Merge data-model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();