madu
madu

Reputation: 354

Beans creation faild in spring

I have an interface like this

public interface InterfaceA {
    public String methodA();
}

and I have implemented it like this

public class ClassA implements InterfaceA {

    @Override
    public String methodA(){
       return "HELLO";
    }
}

I'm trying to reference a bean of this class in another class

public class ClassB {

   @Autowired
   private InterfaceA mybean;

   String str = mybean.methodA();
}

I have the following bean configuration <bean id="mybean" class="ClassA"></bean>

Most interesting point is if I remove all the declaration and implementation of the methodA in InterfaceA and ClassA and then try to just this

public class ClassB {

    @Autowired
    private InterfaceA mybean;

}

no error is shown. In the other case the following error is shown when I try to run this application: "No qualifying bean of type [ClassA] found for dependency"

Upvotes: 0

Views: 40

Answers (1)

Ralph
Ralph

Reputation: 120761

It is because of the livecyle of a bean and a java class!

in your ClassB you have two variables. mybean will been populated by Spring after the object instance ins created (by spring). But String str = mybean.methodA(); will be assinged as soon as the object instance is created. And at this point the variable mybean is still null, and therfor the instance creation will fail!

Solution: use @PostConstruct, spring init-method, or implement InitializingBean -- see this answer for an overview

public class ClassB {

   @Autowired
   private InterfaceA mybean;

   private String str;

   void afterPropertiesSet() {
      String str = mybean.methodA();
   }
}

Upvotes: 1

Related Questions