通过 2.1 版Hazelcast 可以将 Spring 上下文和/或 Spring bean 注入 Hazelcast 托管对象。
如果您使用 Hazelcast Spring 配置配置 Hazelcast 并使用 注释 bean @SpringAware
,Hazelcast 将要求 Spring 注入该 bean 的依赖项。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:hz="http://www.hazelcast.com/schema/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.hazelcast.com/schema/spring
http://www.hazelcast.com/schema/spring/hazelcast-spring-2.1.xsd">
<hz:hazelcast id="instance">
<hz:config>
<hz:group name="dev" password="password"/>
<hz:network port="5701" port-auto-increment="false">
<hz:join>
<hz:multicast enabled="false" />
<hz:tcp-ip enabled="true">
<hz:members>10.10.1.2, 10.10.1.3</hz:members>
</hz:tcp-ip>
</hz:join>
</hz:network>
...
</hz:config>
</hz:hazelcast>
<bean id="someBean" class="com.hazelcast.examples.spring.SomeBean"
scope="singleton" />
...
</beans>
@SpringAware
public class SomeTask implements Callable<Long>, ApplicationContextAware, Serializable {
private transient ApplicationContext context;
private transient SomeBean someBean;
public Long call() throws Exception {
return someBean.value;
}
public void setApplicationContext(final ApplicationContext applicationContext)
throws BeansException {
context = applicationContext;
}
@Autowired
public void setSomeBean(final SomeBean someBean) {
this.someBean = someBean;
}
}
对于早于 2.1 的版本:
Hazelcast 2.1 之前的版本不支持 Spring,因此对于 2.1 之前的版本,无法将 Spring 上下文或任何 Spring bean 注入 Hazelcast 托管对象。
Hazelcast 组上有一篇帖子询问此功能。
可调用的 Hazelcast / 依赖注入
正如您可能已经知道并在 Hazelcast 组中建议的那样,您可以使用以下方法访问 Spring ApplicationContext;
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context = null;
public synchronized void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if(context == null) {
context = applicationContext;
}
}
public static <T> T getBean(String name) {
return (T) context.getBean(name);
}
}
class MyCallable implements Callable {
....
public Object call() throws Exception {
SomeServiceBean bean = ApplicationContextProvider.getBean("serviceBean");
....
}
}