mehta
mehta

Reputation: 755

Load parsed XML objects into Spring context

I have a given XSD and corresponding XML. The constant data in the XML is acting as rules based on which I need to process the input. I am looking for a way I can parse the XML (using the provided schema) at the time of starting application and have the constant data objects thus generated be loaded in the spring context.

So far I am not close, but this is what I tried

  1. Wrote a JaxB parser for the given XML/XSD
  2. The XML file is located at classpath and is being loaded and parsed to return Rule object

<bean id="tcs50MMSplitUtil" class="com.abc.common.SplitRuleService">
  <property name="splitRule" value="classpath:config/Rule50MM.xml" />
</bean>

public class SplitRuleService {

  private static Resource splitRule;

  @Autowired
  private RuleXMLParserHandler splitRuleParser;


  public Rules getSplitRule() throws IOException {
    InputStream io = splitRule.getInputStream();
    return (Rules) splitRuleParser.parse(io);
  }


  public void setSplitRule(Resource splitRule) {
    this.splitRule = splitRule;
  }

}

But this will parse the XML every time this getRule is called. I do not want to parse the constant XML again and again.
I also looked at AbstractBeanDefinitionParser but think that is not what I want.

Any help please. Do let me know if I failed to make my question clear.

Upvotes: 0

Views: 334

Answers (1)

Don Bottstein
Don Bottstein

Reputation: 1660

Define a @PostConstruct method that parses the xml. The method will be called by Spring after construction of the bean and all autowired fields set. Something like:

private Rules rules;

@PostConstruct public void init() {
    InputStream io = splitRule.getInputStream();
    rules = splitRuleParser.parse(io);
}

public Rules getSplitRule() throws IOException {
    return rules;
}

Don't forget to close the input stream.

Upvotes: 1

Related Questions