Ilkar
Ilkar

Reputation: 2177

Spring dynamic autowire services

I've started to build some kind of a CMS and I'm stuck over one idea.

The description is:

I have standard MVC Controller (Home) in which I'm downoading modules settings which will be set in this Controller.

The response is, that I have to implement module with name "HPModule".

So I'm trying to load this module by Class.forName("com.app.something.HPModule"); and then call method init();

My HPModule is:

public class HPModule
{

    @Resource(name = "hpModuleService")
    private HPModuleService hpModuleService;

    public String init()
    {
        SomeObject someObject = hpModuleService.getArticle();
    }
}

And I found that when I'm trying to do SomeObject someObject = hpModuleService.getArticle(); Spring is blind for @Resource when I'm calling class by Class.forName.

How to solve this issue?

Upvotes: 0

Views: 475

Answers (1)

Roadrunner
Roadrunner

Reputation: 6801

The HPModule has to be a Spring Bean retrieved by means of DI or directly from Spring BeanFactory. You cannot expect Spring to autowire a class that is not instantiated by Spring, unless You use @Configurable and AspectJ to weave the class.

If HPModule already is a Spring Bean, than just @Autowire or @Inject it directly into the MVC controller that needs it.

If You don't know in compile time what modules You'll need, than inject ListableBeanFactory and use BeanFactoryUtils to get the modules You need in runtime by type or by name.

Upvotes: 2

Related Questions