View Javadoc

1   /*
2    * Copyright 2005-2010 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.xml.xpath;
18  
19  import java.util.Map;
20  
21  import org.springframework.beans.factory.FactoryBean;
22  import org.springframework.beans.factory.InitializingBean;
23  import org.springframework.util.Assert;
24  import org.springframework.util.CollectionUtils;
25  
26  /**
27   * Spring {@link FactoryBean} for {@link XPathExpression} object. Facilitates injection of XPath expressions into
28   * endpoint beans.
29   * <p/>
30   * Uses {@link XPathExpressionFactory} underneath, so support is provided for JAXP 1.3, and Jaxen XPaths.
31   *
32   * @author Arjen Poutsma
33   * @see #setExpression(String)
34   * @since 1.0.0
35   */
36  public class XPathExpressionFactoryBean implements FactoryBean<XPathExpression>, InitializingBean {
37  
38      private Map<String, String> namespaces;
39  
40      private String expressionString;
41  
42      private XPathExpression expression;
43  
44      /** Sets the XPath expression. Setting this property is required. */
45      public void setExpression(String expression) {
46          expressionString = expression;
47      }
48  
49      /** Sets the namespaces for the expressions. The given properties binds string prefixes to string namespaces. */
50      public void setNamespaces(Map<String, String> namespaces) {
51          this.namespaces = namespaces;
52      }
53  
54      public void afterPropertiesSet() throws IllegalStateException, XPathParseException {
55          Assert.notNull(expressionString, "expression is required");
56          if (CollectionUtils.isEmpty(namespaces)) {
57              expression = XPathExpressionFactory.createXPathExpression(expressionString);
58          }
59          else {
60              expression = XPathExpressionFactory.createXPathExpression(expressionString, namespaces);
61          }
62      }
63  
64      public XPathExpression getObject() throws Exception {
65          return expression;
66      }
67  
68      public Class<? extends XPathExpression> getObjectType() {
69          return XPathExpression.class;
70      }
71  
72      public boolean isSingleton() {
73          return true;
74      }
75  }