class object value is equal to null in Java Spring

89 Views Asked by At

I am working on Java Spring project, where bean of service S is defined in xml file. I have a class A whose method 'getA' is called from urlrewrite.xml rule, and there is a method defined in service S, is used in class A. Upon calling method of class A via defined in urlrewrite.xml file, the value of object 's' in class A is getting null.

Observation: Initialization of object 's' by bean is working fine but when class A is initialized by , it reinitialize the object 's' with value null in class A.

// class A
public class A{
   private S s;  // s = null, this is the problem I am facing
   
   public void getA(){
       Long id = <id>
       s.getData(id);
   }
}


// class S (service)
public class S{
   public Long getData(final Long id){
       return getDatabyId().getId(id);
   }
}

// urlrewrite.xml
<rule>
  <name>xyz</rule>
  <note>xyz note</note>
  <from>.*</from>
  <run class='dir.A' method='getA'>
     <init-param>
        ---params---
     </init-param>
  </run>
</rule>
1

There are 1 best solutions below

0
Navin Kumar On

In Spring We are following AOP programming Paradigm, We have to configure bean in an XML file otherwise it will not create an object for it in the IOC container. Make sure about XML configuration and you can use @Service for class and @Autowired for filed that it gets an object from Container.

   @Service
   public class A{
   @Autowired
   private S s;  // s = null, this is the problem I am facing
   
   public void getA(){
       Long id = <id>
       s.getData(id);
   }
}


@Service
public class S{
   public Long getData(final Long id){
       return getDatabyId().getId(id);
   }
}