本文javaeye同步更新地址:
http://lcllcl987.javaeye.com/blog/351655
spring2以上版本支持自定义标签.
作为一般的应用程序开发人员,扩展spring的标签意义不大。
但如果你是一个平台开发人员,则很有必要拥有一套自己的标签, 提供给应用开发人员使用.
由于mule的标签是基于spring的xml schema扩展的, 为了弄出mule的自定义标签, 今天研究了一下spring的标签扩展, 并笔记之
让我们从一个简单的spring标签制作开始吧。
我需要做的标签如下:
这个标签功能简单, 仅仅打印一下log.它和如下spring bean功能一样:
标签的schema如下:
<xsd:element name="log">
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="beans:identifiedType">
<xsd:attribute name="isPrintTime" type="xsd:boolean" use="required"/>
<xsd:attribute name="company" type="xsd:string"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>
log标签背后的bean如下:
private String company = "";
public LogBean(boolean isPrintTime)
{
this.isPrintTiem = isPrintTime;
}
public void print(String log)
{
if(this.isPrintTiem)
System.out.println(this.company + new Date() + ":" + log);
else
System.out.println(this.company + ":" + log);
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
public boolean isPrintTiem()
{
return isPrintTiem;
}
}
实现一个标签需要扩展一个class:
NamespaceHandlerSupport
并实现一个interface:
public void init()
{
registerBeanDefinitionParser("log",
new LogBeanDefinitionParser());
}
}
LogNamespaceHandler在spring的Ioc容器加载配置文件时,遇到log节点便会调用LogBeanDefinitionParser,完成bean的初始化,并注册到spring context中.
最后在META_INF中, 加入两个配置文件:
spring.handlers和spring.schemas
spring.handlers内容如下:
最后测试一下:
新建一个applicationContext.xml:
<bean id="log" class="co.iplatform.log.LogBean">
<constructor-arg value="true"></constructor-arg>
<property name="company" value="cyberObject"></property>
</bean>
</beans>
testcase:
public void testLogBean()
{
LogBean logBean = (LogBean)this.applicationContext.getBean("iplatformLog");
assertTrue(StringUtils.hasText(logBean.getCompany()));
assertTrue(logBean.isPrintTiem());
logBean.print("is fun!");
}
}
绿色在期待中出现.
为了让mule使用这个bean, 只需mule的配置文件导入上面的spring的Application.xml
然后定义一个mule:
写一个mule的测试: