milo
milo

Reputation: 477

Spring is not injecting a property

I want to inject port value from xml file but it seems not working. Here is my xml file, what am I doing wrong?.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    
    <bean id="serverSocket" class="some.dir.KomunikacjaSpring.ServerSocketMy">
        <property name="port" value="3111" />
        <property name="port2" value="911" />
    </bean>
    <bean id="server" class="some.dir.KomunikacjaSpring.Server">
        <constructor-arg ref="serverSocket" />
    </bean>

</beans>

I'm trying to inject port value inside my ServerSocket class.

public class ServerSocketMy extends ServerSocket {
    
    
    static int port = 6066;
    int port2;

    public ServerSocketMy() throws IOException {
        super(port);
        System.out.println("PORT2: "+port2);
    }

    public int getPort() {
        return port;
    }
    
    public void setPort(int port) {
        this.port = port;
    }
    
    public void setPort2(int port2) {
        this.port2 = port2;
    }
    
    
}

When program is running everything works perfectly but port value is not changing.

Upvotes: 1

Views: 366

Answers (1)

nobeh
nobeh

Reputation: 10049

Study bean lifecycle and dependency injection in more depth. For your example, note:

  • MySocketServer is constructed in one phase.
  • The properties are injected in another phase.
  • The value of port2 is still 0 (default value) during construction.
  • You can use constructor argument instantiation

Upvotes: 2

Related Questions