使用构造函数自动装配对象

时间:2013-04-10 06:47:23

标签: java spring dependency-injection

我需要从spring factory获取一个对象,该对象有一个构造函数参数,其值在运行时指定。我该怎么做呢。如果我没有任何构造函数,这很有效。

@Service
public class PortService implements Runnable {

@Autowired
LeaveProcessor leaveProcessor;

private Socket socket;

public PortService(Socket socket) {
    this.socket = socket;
}

public void run() {
    PrintWriter writer;
    BufferedReader reader;
    try {
        reader = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        String message = reader.readLine();
        writer = new PrintWriter(socket.getOutputStream(), true);
        writer.println(leaveProcessor.process(message));
        writer.close();
        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

编辑 - 没有构造函数我可以通过直接访问Autowireed对象leaveProcessor来使其工作。

套接字:这是从工厂加载的:

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

}

2 个答案:

答案 0 :(得分:0)

您需要实现工厂bean

public class PortServiceFactory implements FactoryBean<PortService> {
     PortService getObject() {
         Socket socket;
         // Code to initialize the socket
         return new PortService(socket);
     }
     // FactoryBean interface requires a couple of other methods,
     // implement those
}

答案 1 :(得分:0)

从context.xml文件本身传递构造函数参数。

    <bean id="theBeanID" class="your.package.PortService" >
       <constructor-arg ref="socketBeanID"  />  
     </bean>

    <bean id="socketBeanID" class="your.package.Socket" />

我不知道你是如何创建Socket对象的,但它必须传递给xml上下文文件本身的构造函数。

如果可以避免使用构造函数,请自动装入Socket类本身。

@Autowired
private Socket socket;

或者,使用 new 关键字在您的类PortService中实例化它。

OR,使用一些静态工厂方法,如果需要,可以创建Socket对象。