简体   繁体   中英

Spring Annotation Configuration in a library

I have made several applications which use a pure annotation Spring configuration. Now, I would like to try to build a library.

  • The library should use pure annotation Spring configuration.
  • Projects which use the library should be able to use the library without any special Spring configuration. Indeed, I want the library to be usable interchangeably with Spring and non-Spring projects. All Spring configurations should be handled within the library jar.
  • The library should be usable in projects that are not web applications.
  • Applications using the library should be able to instantiate public classes in the library with the new keyword, and for their @Autowired dependencies to be resolved.

I am not sure how one would go about doing this. There would need to be some way of establishing the application context, and this seems to be done at the insertion point. Since libraries have no insertion point, I am at a loss.

Is this just something that is not done? Spring dependency injection seems to be a very useful tool and it would be a shame if I couldn't use it to build libraries.

From what you write, your libraries will essentially be a grouping of custom components that are internally consistent and have explicit dependencies defined to other libraries through META-INF Class-path or Maven dependency definition.

There is no magic to annotations. Annotations are simply markers that are processed by an annotation processor, so without a framework annotation processor that does the auto-wiring, the annotations are little more than comments. The same is true of JAXB or JPA annotations.

Your non-Spring applications will need to instantiate an initial container and then start the binding process per IoC principles. One of your libraries can be such a 'boot' library that initiates this process and has code that can read bean configuration, or scan components, from inside your other library jars and auto-wire components from different libraries.

In short, you will need some form of booting, which can be an additional 'boot' library by itself. You can make this boot library minimal and almost transparent to the non-Spring application and provide some form of component lookup but it will be very hard to do it in a completely transparent manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM