0

I'm fairly new to the the Spring and I'm trying to move our legacy code to spring.I'm trying to auto inject all the dependencies by using @Autowired.

My Bean has a factory method as follows:

public static Service getInstance(Registration registration) throws Exception {
    Service service = null;
    switch(registration.getType()) {
        case XServer : 
            service = new XServer(); break;
        case YServer : 
            service = new YServer(); break;
        default : 
            service = new XServer(); break;
    }

    service.setRegistration(registration);
    return service;
}

But when I use new in the factory method all the dependencies in the new class remains uninitialized. Also if I use appContext.getBean('beanname') it throws following exception:

Requested bean is currently in creation: Is there an unresolvable circular reference?

Can some one help me understand how to do it correct.

2 Answers2

0

If I understand you right, then you are trying to instantiate the factory manually via the new command. But the Spring framework must register the beans, when you are trying to use them in the ApplicationContext. You have to create a Factory Bean which provides the creation of common other objects. These objects also have to be registered to the Spring config of your application.

Have a look at the Spring documentation

That means you have to define somewhere in your application beans of following types: XServer, YServer and the type of your Factory Bean. Furthermore you should have a look at Method Injection, because you are trying to create beans with different scopes.

a.ha
  • 519
  • 4
  • 20
0

I've had a similar problem, but found this question helpful: Inject spring dependency in abstract super class. It's not exactly the same, but it handles the point of inheritance. Note that it's using XML instead of annotations.

Community
  • 1
  • 1
Br2
  • 167
  • 1
  • 10