我必须编写一个接受套接字连接的类,并使用Spring将其传递给Handler类。

我的监听器类是

public class Listener {

    static Logger log = Logger.getLogger(Listener.class.getName());

    public static void main(String args[]) throws IOException {
    int port = 0;
        if (args.length < 1) {
            System.out.println("Usage: java -jar hovel.jar listenPortNumber");
            System.exit(1);
        } else {
            port = Integer.parseInt(args[0]);
        }
         ApplicationContext context =
                 new ClassPathXmlApplicationContext("Beans.xml");
            ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("TCPHandler");

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Listening on TCP port " + port);
        for (;;) {
            Socket sock = serverSocket.accept();
            taskExecutor.execute(new TCPHandler(sock));

        }
    }

}


我的处理程序类是

public class TCPHandler implements Runnable {
    private Socket moduleSocket;



    public TCPHandler(Socket sock) {
        moduleSocket = sock;
    }

    public void run() {

    }

}


我的Bean.xml是

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="TCPHandler" class="org.hovel.server.TCPHandler">
   <constructor-arg type="java.net.Socket">
        <null />
    </constructor-arg>
   </bean>
   <bean id="taskExecutor"
        class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="5" />
        <property name="maxPoolSize" value="10" />
        <property name="WaitForTasksToCompleteOnShutdown" value="true" />
    </bean>
</beans>


当我通过端口号时,我得到了这个错误
**


线程“主”中的异常java.lang.ClassCastException:
org.hovel.server.TCPHandler无法转换为
org.springframework.scheduling.concurrent.ThreadPoolTask​​Executor在
org.hovel.server.Listener.main(Listener.java:27)*


**

请帮我

最佳答案

您在这里请求TCPHandler bean:

context.getBean("TCPHandler")


那不是ThreadPoolTaskExecutor,所以我不知道你为什么会这样。如果要检索执行程序,则应该获取该ID为taskExecutor的bean。

请注意,当前您实际上并没有以任何有用的方式使用TCPHandler bean,因为您正在TCPHandler方法中显式构造main

07-24 09:26