0

I have tried to initialize setter method from context file.But it isn't working as expected.

//setter method

public class Service {

    private long Id=0;

    public long getId() {
        return Id;
    }
    public void setId(long Id) {
        this.Id = Id;
    }

}

//calling method

public class test {

    //...source code
    Service sercvi = new Service();
    System.out.println("******************ID"+sercvi.getId());
    .................................. 

}

Context.xml

    ..........................................
    ..........................................
    <bean id="Service"  class="com.test.Service.Service" > 
      <property name="Id" value="100"/> 
    </bean>
   ...........................................
   ..........................................

Here goes loading context file in web.xml file web.xml

...............................
    ....................
    <!-- Spring load context.xml - -->
    <context-param>
        <param-name>contextLocation</param-name>
        <param-value>/WEB-INF/Context.xml</param-value>
    </context-param>

If i run the application it always return 0 value for id but i have initalized 100 in context.xml. Why that value is not retrieved ? How to initlialize setter method value from context file? Also how to retrieve those value?

How to resolve this error?

Ami
  • 4,241
  • 6
  • 41
  • 75

1 Answers1

2

Your Service instance is being created manually. Spring will only fire the injections when your bean is handled by the Spring context.

How to resolve this error?

Do not initialize your beans manually, recover them using Spring context or by Spring injection.

You may inject the bean inside another bean:

@Component
public class FooComponent {
    @Autowired
    Service service;
    public void foo() {
        System.out.println(service.getId()); //prints the value injected by Spring
    }
}

Or recover it directly from the Spring context

@Component
public class BarComponent {
    @Autowired
    BeanFactory beanFactory;
    void bar() {
        Service service = (Service)beanFactory.get("service");
        System.out.println(service.getId()); //prints the value injected by Spring
    }
}

There's another option that let you create the beans manually and getting all the Spring power within them by using @Configurable annotation as explained here.


In case you want to test your Spring beans, use JUnit + Spring Test, but this is more used for integration testing rather than unit testing.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(location={"classpath:location/of/your/spring.xml"})
public class MySpringTest {
    @Autowired
    Service service;

    @Test
    public void fooTest() {
        System.out.println(service.getId());
        Assert.assertEquals(100, service.getId());
    }
}
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332