Java教程

Spring源码-自定义标签

本文主要是介绍Spring源码-自定义标签,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、新建实体类

    public class User implements Serializable {
private String id;

private String name;

private Integer age;

public String getId() {
	return id;
}

public void setId(String id) {
	this.id = id;
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public Integer getAge() {
	return age;
}

public void setAge(Integer age) {
	this.age = age;
}

@Override
public String toString() {
	final StringBuffer sb = new StringBuffer("User{");
	sb.append("id='").append(id).append('\'');
	sb.append(", name='").append(name).append('\'');
	sb.append(", age=").append(age);
	sb.append('}');
	return sb.toString();
}
  }

二、新建xsd文件

    <?xml version="1.0" encoding="UTF-8"?>
    <schema xmlns="http://www.w3.org/2001/XMLSchema"
    		targetNamespace="http://www.myself.com/schema/user"
    		xmlns:tns="http://www.myself.com/schema/user"
    		elementFormDefault="qualified">
    	<element name="user">
    		<complexType>
    			<attribute name ="id" type = "string"/>
    			<attribute name ="name" type = "string"/>
    			<attribute name ="age" type = "integer"/>
    		</complexType>
    	</element>
    </schema>

三、新建NamespaceHandler和BeanDefinitionParser

    public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
  @Override
  protected Class<?> getBeanClass(Element element) {
		return User.class;
	  }

@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
	if (element.hasAttribute("id")) {
		builder.addPropertyValue("id", element.getAttribute("id"));
	}
	if (element.hasAttribute("name")) {
		builder.addPropertyValue("name", element.getAttribute("name"));
	}
	if (element.hasAttribute("age")) {
		builder.addPropertyValue("age", element.getAttribute("age"));
	}
    }
    }

    public class UserNamespaceHandler extends NamespaceHandlerSupport {
    @Override
	  public void init() {
  		registerBeanDefinitionParser("user", new UserBeanDefinitionParser ());
  	  }
    }

四、在resources目录下建立META-INF目录并新建spring.handlers和spring.schemas

spring.handlers

    http\://www.myself.com/schema/user=selftag.UserNamespaceHandler

spring.schemas

    http\://www.myself.com/schema/user.xsd=META-INF/user.xsd

五、使用

在app-test.xml文件的beans标签中加入

    xmlns:aaa="http://www.myself.com/schema/user"
    http://www.myself.com/schema/user http://www.myself.com/schema/user.xsd

bean定义

    <aaa:user name="李四" id="123" age="45"></aaa:user>

运行

    ApplicationContext applicationContext = new MyClassPathApplicationContext("classpath:app-${user}.xml");
    User user = applicationContext.getBean(User.class);
System.out.println(user);

这篇关于Spring源码-自定义标签的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!