在開發Dubbo應用的時候,咱們會在xml中作如下相似的配置:java
<dubbo:application name="dubbo_service_provider" /> <dubbo:registry address="zookeeper://127.0.0.1:2181" /> <dubbo:protocol name="dubbo" port="20880" />
spring啓動後,Dubbo的本地運行時環境就會獲取到這些信息,根據這些信息完成註冊服務,今天咱們實戰的內容就是開發一個相似的自定義屬性,而後在spring項目中使用這個屬性;git
整個實戰過程分爲如下幾步:程序員
若是您不打算編碼,也能夠在GitHub下載本次實戰的源碼,地址是:https://github.com/zq2599/blog_demos ,裏面有多個工程,本次用到的是springschemademo,以下圖紅框所示:github
接下來開始實戰:web
建立一個maven工程,pom.xml的內容以下,主要是把spring相關的依賴引入:spring
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bolingcavalry</groupId> <artifactId>springschemademo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>app Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本號 --> <spring.version>4.0.2.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示開發的時候引入,發佈的時候不會加載此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <!-- 導入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- JSTL標籤類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上傳組件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <!-- 是否替換資源中的屬性--> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>tomcat7</server> <path>/${project.artifactId}</path> <update>true</update> </configuration> </plugin> </plugins> </build> </project>
web.xml中加上spring mvc的配置:apache
<servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此處能夠能夠配置成*.do,對應struts的後綴習慣 --> <url-pattern>/</url-pattern> </servlet-mapping>
還有spring的配置文件,加上註解相關的配置:centos
<!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- JSON轉換器 --> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean>
其他的配置能夠自行設置,或者參考我上傳到git上的源碼;api
本次實戰的示例,以"電腦"爲例,有兩個屬性:操做系統和內存大小,以下:瀏覽器
package com.bolingcavalry; /** * Description: * * @author willzhao * @email zq2599@gmail.com * @date 2017/7/1 22:15 */ public class Computer { /** * 操做系統 */ private String os; /** * 內存大小 */ private int ram; public String getOs() { return os; } public void setOs(String os) { this.os = os; } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; } }
在工程的src\main\resources\META-INF\computer.xsd目錄下建立computer.xsd文件,內容以下:
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns="http://blog.csdn.net/boling_cavalry/schema/computer" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:beans="http://www.springframework.org/schema/beans" targetNamespace="http://blog.csdn.net/boling_cavalry/schema/computer" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xsd:import namespace="http://www.springframework.org/schema/beans"/> <xsd:element name="computer"> <xsd:complexType> <xsd:complexContent> <xsd:extension base="beans:identifiedType"> <xsd:attribute name="os" type="xsd:string"/> <xsd:attribute name="ram" type="xsd:int"/> </xsd:extension> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:schema>
注意xmlns和targetNamespace的內容,在外部使用時也會用到,還有就是xsd:element節點,裏面對computer的兩個屬性作了約束;
接下來要寫個BeanDefinitionParser,做用是拿到xml中的computer節點後,該如何從這個節點中取得有效的信息給spring環境,源碼以下:
public class ComputerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { @Override protected Class<?> getBeanClass(Element element) { return Computer.class; } @Override protected void doParse(Element element, BeanDefinitionBuilder builder) { String os = element.getAttribute("os"); String ramStr = element.getAttribute("ram"); if(StringUtils.hasText(os)){ builder.addPropertyValue("os", os); } if(StringUtils.hasText(ramStr)){ builder.addPropertyValue("ram", Integer.valueOf(ramStr)); } } }
getBeanClass方法決定了解析節點後返回的bean的類型; doParse方法的入參中收到了computer節點,在方法中解析"os"和"ram"兩個節點,而後調用builder.addPropertyValue能夠把解析結果傳入builder中;
自定義的NamespaceHandler,能夠告訴spring環境,遇到computer的配置信息後,應該用ComputerBeanDefinitionParser去解析,代碼不多,以下:
public class ComputerNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("computer", new ComputerBeanDefinitionParser()); } }
在src\main\resources\META-INF\目錄下,添加spring.handlers文件,內容只有一行,以下:
http\://blog.csdn.net/boling_cavalry/schema/computer=com.bolingcavalry.ComputerNamespaceHandler
在src\main\resources\META-INF\目錄下,添加spring.schemas文件,內容只有一行,以下:
http\://blog.csdn.net/boling_cavalry/schema/computer.xsd=META-INF/computer.xsd
準備得差很少了,能夠驗證一下啦,在spring的配置文件中,若是要用到這個屬性,能夠按照以下方式來寫:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:bolingcavalry="http://blog.csdn.net/boling_cavalry/schema/computer" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://blog.csdn.net/boling_cavalry/schema/computer http://blog.csdn.net/boling_cavalry/schema/computer.xsd"> <bolingcavalry:computer id="computer" os="centos" ram="8" /> </beans>
除了bolingcavalry:computer的配置,還要注意xmlns:bolingcavalry的配置,還有xsi:schemaLocation中「http://blog.csdn.net/boling_cavalry/schema/computer"和 "http://blog.csdn.net/boling_cavalry/schema/computer.xsd」 也不要遺漏。
爲了驗證配置是生效的,咱們寫一個controller在瀏覽器中顯示配置信息,代碼以下:
@Controller public class HelloController { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Autowired Computer computer; @RequestMapping("/hello") @ResponseBody public String toIndex(HttpServletRequest request, Model model) { return "hello 001 [" + sdf.format(new Date()) + "], computer os [" + computer.getOs() + "], ram [" + computer.getRam() + "]"; } }
computer提供autowire注入,在web響應的時候會輸出它的兩個屬性,如今啓動tomcat並部署這個webapp,在瀏覽器中輸入http://localhost:8080/springschemademo/hello, 就能看到以下輸出:
以上就是spring自定義schema的實戰內容,這裏只是爲了快速體驗這個功能,實際的應用中應該是把這種能力封裝到庫中,而後提供給應用方來使用。