pf4j / pf4j-spring

Plugin Framework for Spring (PF4J - Spring Framework integration)
Apache License 2.0
346 stars 105 forks source link

Injecting beans from plugin in application doesn't work #69

Open daincredibleholg opened 3 years ago

daincredibleholg commented 3 years ago

Hi.

We are currently building a Spring Boot-based service that will use plugins to make it highly customizable for our users.

One thing we try to do is providing beans via plugins that can be injected by the host application.

From what I found so far, it looks like the plugin manager isn't instantiated yet when Spring tries to resolve all injectable dependencies. To make this (hopefully) a bit easier to understand, here is an example project

In the given example, I try to inject a bean from the plugin into the main application. This results in the application not even starting, as Spring doesn't seem to find the bean it needs to inject.

Later, we would like to use plugins to provide database connections. So, we would need @Configuration classes and injection working within and from the plugin.

Is this possible? Are there examples I can have a look at?

jingsewu commented 11 months ago

Yes ,In my project. I can't obtain the bean from the spring contain too. My code is below:

@Autowired
private ApplicationContext applicationContext;

@Override
public void afterDoOperation(String string) {
    log.info("plugin logging:" + string);
    Object dictionaryController = applicationContext.getBean("dictionaryController");
    System.out.println(dictionaryController);
}

The dictionaryController is null. I think the reason is when we start the plugin we will new AnnotationConfigApplicationContext(); . so when we use @Autowired , it will query the bean from the new application context . not the main application context.

So you need to add the code: applicationContext.setParent(((SpringPluginManager) getWrapper().getPluginManager()).getApplicationContext()); When you create the applicationContext in you SpringPlugin Class.

decebals commented 11 months ago

I don't use Spring with PF4J in my projects and from this reason I don't have a rich expertise on this subject. Please read https://github.com/pf4j/pf4j-spring/issues/27#issuecomment-451374334, and take a look on Spring ApplicationContext hierarchies.