关闭

apache mina 学习(十四)-----与spring整合

标签: minaspringapachebeanclassexception
9300人阅读 评论(3) 收藏 举报
分类:

mina与spring整合的主要问题就是mina中一些bean的配置需要spring的ioc,我们首先看一个简单的服务端代码:

public void initialize() throws IOException {

	// Create an Acceptor
	NioDatagramAcceptor acceptor = new NioDatagramAcceptor();

	// Add Handler
	acceptor.setHandler(new ServerHandler());

	acceptor.getFilterChain().addLast("logging",
				new LoggingFilter());
	acceptor.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new SNMPCodecFactory()));

	// Create Session Configuration
	DatagramSessionConfig dcfg = acceptor.getSessionConfig();
        dcfg.setReuseAddress(true);
        logger.debug("Starting Server......");
        // Bind and be ready to listen
        acceptor.bind(new InetSocketAddress(DEFAULT_PORT));
        logger.debug("Server listening on "+DEFAULT_PORT);
}
整合步骤一般有三步:1、设置io handler 2、创建filters 3、创建socket

spring中设置iohandler:

<!-- The IoHandler implementation -->
  <bean id="trapHandler" class="com.ashishpaliwal.udp.mina.server.ServerHandler" />
Filters:

<bean id="snmpCodecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
    <constructor-arg>
      <bean class="com.ashishpaliwal.udp.mina.snmp.SNMPCodecFactory" />
    </constructor-arg>
  </bean>

  <bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" />

  <!-- The filter chain. -->
  <bean id="filterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">
    <property name="filters">
      <map>
        <entry key="loggingFilter" value-ref="loggingFilter"/>
        <entry key="codecFilter" value-ref="snmpCodecFilter"/>
      </map>
    </property>
  </bean>

我们用的是基于构造方法的注入方式,最后我们注入socket:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
      <map>
        <entry key="java.net.SocketAddress">
          <bean class="org.apache.mina.integration.beans.InetSocketAddressEditor" />
        </entry>
      </map>
    </property>
 </bean>

<!-- The IoAcceptor which binds to port 161 -->
<bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioDatagramAcceptor" init-method="bind" destroy-method="unbind">
    <property name="defaultLocalAddress" value=":161" />
    <property name="handler" ref="trapHandler" />
    <property name="filterChainBuilder" ref="filterChainBuilder" />
</bean>
这样我们可以在spring容器中获得mina的服务器实例了:

public void initializeViaSpring() throws Exception {
    new ClassPathXmlApplicationContext("trapReceiverContext.xml");
}



1
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:243037次
    • 积分:3579
    • 等级:
    • 排名:第9470名
    • 原创:115篇
    • 转载:23篇
    • 译文:0篇
    • 评论:23条
    文章分类
    最新评论