Spring中SimpleNamingContextBuilder已弃用,求替代实现方案
替代Spring SimpleNamingContextBuilder的方案实现
Spring官方从5.2版本开始弃用SimpleNamingContextBuilder,推荐使用Simple-JNDI这类第三方内存型JNDI实现来替代,以下是具体改造方案:
1. 引入Simple-JNDI依赖
在项目中添加测试环境依赖(仅在测试阶段使用):
<!-- Maven依赖 --> <dependency> <groupId>org.osjava</groupId> <artifactId>simple-jndi</artifactId> <version>0.11.4.1</version> <scope>test</scope> </dependency>
2. 改造SMNContextBuilder类
替换原有Spring Mock实现,基于Simple-JNDI实现对象绑定逻辑:
import org.osjava.sj.SimpleContext; import org.springframework.beans.factory.InitializingBean; import javax.naming.Context; import javax.naming.NamingException; import java.util.Iterator; import java.util.Map; public class SMNContextBuilder implements InitializingBean { private Map<String, Object> ncMap; private SimpleContext jndiContext; @Override public void afterPropertiesSet() throws Exception { if (ncMap == null) { throw new IllegalStateException("ncMap is null!"); } initJndiContext(); bindObjects(); } private void initJndiContext() throws NamingException { // 初始化Simple-JNDI内存上下文 jndiContext = new SimpleContext(); // 配置JNDI环境,让后续InitialContext能获取到该上下文 System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.SimpleContextFactory"); System.setProperty("org.osjava.sj.root", ""); // 无需指定根目录,直接绑定 System.setProperty("org.osjava.sj.delimiter", "/"); System.setProperty("org.osjava.sj.jndi.shared", "true"); // 开启上下文共享 } protected void bindObjects() throws NamingException { for (Iterator<Map.Entry<String, Object>> iter = ncMap.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, Object> entryTmp = iter.next(); jndiContext.bind(entryTmp.getKey(), entryTmp.getValue()); } } public void setNamingContextMap(Map<String, Object> ncMapPar) { this.ncMap = ncMapPar; } }
3. 测试配置类无需大幅调整
原有的测试配置类可以直接复用,因为SMNContextBuilder对外接口未改变:
@Configuration public class MQTestConfig { @Bean public SMNContextBuilder jnidInitializingBean() throws JMSException { SMNContextBuilder builder = new SMNContextBuilder(); Map<String, Object> map = new HashMap<>(); map.put("java:comp/env/jms/My_ConFac", myConnectionFactory()); map.put("jms/My_Queue", myQueue()); builder.setNamingContextMap(map); return builder; } // 以下为示例实现,根据实际测试场景调整 private ConnectionFactory myConnectionFactory() throws JMSException { return new org.apache.activemq.junit.EmbeddedActiveMQBroker().createConnectionFactory(); } private Queue myQueue() { return new ActiveMQQueue("My_Queue"); } }
关于你之前的尝试说明
直接使用InitialContext无法实现绑定的原因是:默认的JNDI上下文没有内存存储能力,必须指定对应的ContextFactory。Simple-JNDI提供的SimpleContextFactory可以创建可读写的内存JNDI上下文,完全适配测试场景的需求。
内容的提问来源于stack exchange,提问作者razib017
相关产品推荐
相关产品推荐

