spring 自定义标签

一、首先建立一个标签对应的实体类User

 

public class User {
	private String userName;
	private String email;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}

二、建立解析自定义标签的类 UserBeanDefinitionParser

package vip.spring.demo.customTag;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

	protected Class getBeanClass(Element element) {
		return User.class;
	}

	protected void doParse(Element element, BeanDefinitionBuilder bean) {
		String userName = element.getAttribute("userName");
		String email = element.getAttribute("email");

		if (StringUtils.hasText(userName)) {
			bean.addPropertyValue("userName", userName);
		}
		if (StringUtils.hasText(email)) {
			bean.addPropertyValue("email", email);
		}
	}
}

三、建立处理的类 NamespaceHandlerSupport,这个类主要用来调用解释类

package vip.spring.demo.customTag;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class MyNamespaceHandler extends NamespaceHandlerSupport {

	public void init() {
		registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
	}

}

四、建立xsd 文件,用来校验我们的自定义标签的有效性



	
		
			
			
			
		
	

五、spring读取我们自定义的schema和handlers默认是根据spring.handlers和spring.schemas来读取的,这两个文件默认要放在META-INF下

具体配置:

spring.handlers

http\://www.lexueba.com/schema/user=vip.spring.demo.customTag.MyNamespaceHandler

spring.schemas

http\://www.lexueba.com/schema/user.xsd=META-INF/spring-test.xsd

六、配置完毕后,我们就可以使用自定义标签了,建立test.xml.建立的时候,如果eclipse没有提示,可以在Preferencers -> XML Catalog 下添加我们刚刚的xsd

spring 自定义标签_第1张图片

test.xml 



   

最后,编写test的文件  SpringCustomTest.java

package vip.spring.demo.customTag;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringCustomTest {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("test.xml");
		User user = (User) ac.getBean("testBean");
		System.out.println(user.getUserName());
	}

}


整个项目目录如下:

spring 自定义标签_第2张图片

项目 pom.xml


		UTF-8
	

	
		
			org.springframework
			spring-core
			3.2.3.RELEASE
		
		
			org.springframework
			spring-test
			3.2.0.RELEASE
		
	

	
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.2
				
					1.7
					1.7
					UTF8
				
			
		
	





你可能感兴趣的:(spring)