自定义标签,用来实现定义Bean的作用范围线程独立,每个线程产生自己的实例对象
对象类
public class Model {
}
标签处理类
public class ThreadScopeHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("thread", new ThreadScopeBeanDefinitionParser());
}
}
BeanDefinitionParser
public class ThreadScopeBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
protected Class getBeanClass(Element element) {
return CustomScopeConfigurer.class;
}
protected void doParse(Element element, BeanDefinitionBuilder bean) {
Map<String, Object> scopes = new HashMap();
if (!scopes.containsKey("thread")) {
SimpleThreadScope simpleThreadScope = new SimpleThreadScope();
scopes.put("thread", simpleThreadScope);
bean.addPropertyValue("scopes", scopes);
}
}
}
spring.handlers
http\://www.zheng.com/schema/scope=org.dataguru.ThreadScopeHandler
spring.schemas
http\://www.zheng.com/schema/scope.xsd=scope.xsd
scope.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.zheng.com/schema/scope" targetNamespace="http://www.zheng.com/schema/scope"
elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="thread">
<xsd:complexType>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
mybeans.xml
<?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:scope="http://www.zheng.com/schema/scope"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.zheng.com/schema/scope http://www.zheng.com/schema/scope.xsd">
<bean id="cc" class="org.dataguru.Model" scope="thread"/>
<!--必须要有一个id,否则会报Configuration problem: Id is required for element 'thread' when used as a top-level tag的错误..-->
<scope:thread id="threadscope"/>
</beans>
测试类
public class ThreadScopeTest {
public static void main(String[] args) throws InterruptedException {
final ApplicationContext ac = new ClassPathXmlApplicationContext("mybeans.xml");
System.out.println("主线程对象比较是否相同:"+(ac.getBean("cc") == ac.getBean("cc")));
new Thread(new Runnable() {
@Override
public void run() {
Model model1 = (Model) ac.getBean("cc");
System.out.println("线程一:model1.hash=" + System.identityHashCode(model1));
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Model model2 = (Model) ac.getBean("cc");
System.out.println("线程二:model2.hash=" + System.identityHashCode(model2));
}
}).start();
}
}
执行结果:
可以看到同在一个主线程的两个对象是相等的,在不同线程产生的对象是不相等的。
项目完整代码:
https://github.com/difffate/SpringProjects