【问题标题】:Autowiring in case of Constructor with parameters for socket在带有套接字参数的构造函数的情况下自动装配
【发布时间】:2013-04-10 06:08:48
【问题描述】:

我的主要代码

public static void main(String[] args) {
    System.out.println("Hello World!");
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "DataSource.xml");
    App app = applicationContext.getBean(App.class);
    app.start();
}

还有我的启动方法

public void start() {

    try {
        ServerSocket mobCom = new ServerSocket(9846);
        ExecutorService executorService = Executors.newCachedThreadPool();

        while (true) {
            Socket socket = mobCom.accept();
            PortService portService = new PortService(socket);
            executorService.submit(portService);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

但我希望 PortService 对象从 Spring 而不是直接创建,因为它具有用于通信的 db 类。我该怎么做。

【问题讨论】:

    标签: java spring dependency-injection inversion-of-control autowired


    【解决方案1】:

    我过去通过这样做实现了这一目标-

    为您的 PortService 实现一个工厂类。

    @Service
    public class PortServiceFactory {
        private SomeObject someObject;
    
        @Autowired
        public PortServiceFactory(SomeObject someObject) {
            this.someObject = someObject;
        }
    
        public PortService getPortService(Socket socket) {
            return new PortService(someObject, socket);
        }
    }
    

    在你有 start() 方法的类中自动装配这个工厂。

    替换

    PortService portService = new PortService(socket);
    

    PortService portService = portServiceFactory.getPortService(socket);
    

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      相关资源
      最近更新 更多