Skip to content
Advertisement

when there are some classes which may not exist, how should I manage them in an XxxAutoConfiguration?

JavaScript

In my starter project, I will write a XxxAutoConfiguration that uses AFactory or BFactory.

I’ve tried:

JavaScript

but it doesn’t work.

I know I can write three AutoConfiguration respectively with @ConditionalOnBean(AFactory.class), @ConditionalOnBean(BFactory.class) and @ConditionalOnMissingBean(....) to solve the problem, but it’s far from elegant… do you have any good solution? Thanks a lot.

Advertisement

Answer

Writing code that uses a class that may not exist on the classpath at runtime is not good idea. Writing the code so it doesn’t cause NoClassDefFoundError is troublesome.

The standard Spring Boot way can e.g. be seen in the source code of DataSourceConfiguration.

In your case, you can do this:

JavaScript

As you can see, you can do it using @Autowired or using a parameter, either way should work.

In case both AFactory and BFactory are present on the classpath, you can e.g. use @AutoConfigureOrder to specify which one wins, as shown here. There are other @ConditionalXxx annotations for more complex ways.

The XxxAutoConfiguration class is really just a pseudo-package for keeping it all together.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement