本篇内容介绍了“spring怎么自定义属性”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
在开发Dubbo应用的时候,我们会在xml中做以下类似的配置:
<dubbo:application name="dubbo_service_provider" /> <dubbo:registry address="zookeeper://127.0.0.1:2181" /> <dubbo:protocol name="dubbo" port="20880" />
spring启动后,Dubbo的本地运行时环境就会获取到这些信息,根据这些信息完成注册服务,今天我们实战的内容就是开发一个类似的自定义属性,然后在spring项目中使用这个属性;
整个实战过程分为以下几步:
创建web工程;
创建配置属性的bean;
创建XSD文件;
创建自定义BeanDefinitionParser,制定配置信息的解析规则;
创建自定义NamespaceHandler,规定配置信息的解析器;
添加spring.handlers文件;
添加spring.schemas文件;
在工程中配置一个这样的属性;
启动web工程,验证配置;
如果您不打算编码,也可以在GitHub下载本次实战的源码,地址是:https://github.com/zq2599/blog_demos ,里面有多个工程,本次用到的是springschemademo,如下图红框所示:
接下来开始实战:
创建一个maven工程,pom.xml的内容如下,主要是把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的配置:
<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的配置文件,加上注解相关的配置:
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- JSON转换器 --> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean>
其余的配置可以自行设置,或者参考我上传到git上的源码;
本次实战的示例,以"电脑"为例,有两个属性:操作系统和内存大小,如下:
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怎么自定义属性”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。