Techiio-author
Started by Chris GillNov 5, 2021

Open
How to load beans according to Spring java conf from jar dynamically?

4 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 4 VIEWES SHARE

I have such app conf in, jar so that you can be brought to the classpath after startup:

@Configuration
@ComponentScan("com.transportexchangegroup.testConf")
public class AppConf {
   
}

How to load beans dynamically? I saw solutions whilst it's miles required to jot down and upload bean definitions, but if we do not recognize everything approximately new beans and simply need to load them routinely?

Class conf = jarService.loadClass("com.x.testConf.AppConf");
((AnnotationConfigServletWebServerApplicationContext) applicationContext).register(conf);
((AnnotationConfigServletWebServerApplicationContext) applicationContext).refresh();

As I see, refresh() turns off web app started locally from IDE.

1 Replies

Techiio-commentatorArchana Behera replied 3 months ago0 likes0 dislikes

you can load beans if some condition applies, usually depending on the configuration. like:

application.properties

feature.enabled=true
@Component
@ConditionalOnProperty(name="feature.enabled", havingValue="true", matchIfMissing="true" / "false")
public MyBean {

}

If you have more beans that depend on "business" feature in order to avoid placing @ConditionalOnProperty you can do one of the following:

  1. Define your own @Component annotation:

@Component
@ConditionalOnProperty(...)
@MyFeatureComponent

... and use it in all the beans that define the feature:

@MyFeatureComponent
public class MyBean
{}

Use Java Configuration instead of annotations:

@Configuration
@ConditionalOnProperty(...)
public class MyFeatureConfiguration {

@Bean
public MyBean myBean(){return new MyBean();}

@Bean
public MyAnotherBean myAnotherBean(){return new MyAnotherBean();}

}

In this case you don't need to place any annotation on MyBean at all.

You must be Logged in to reply
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance