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

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");
}



阅读更多
个人分类: mina
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭