I want to use data mappers, logger, transfromers, etc. in my Spring web projects. Is it possible to autowire an imported (jar) utility dependency, without wrapping it in some @Component or @Service class? Do we even want to do it that way, or should we just use a static reference?
2 Answers
If your utils, are based on not static methods, then this is simple:
If you use java based configuration, then just declare that util in an @Bean
annotated method.
@Configuration
public class YourConfig {
@Bean
public YourUtil util(){
return new YourUtil ();
}
}
in xml it could been as simple as:
<bean id="util" class="org.example.YourUtil" />
The following is true, but it is not what was asked for:
There are at least two other ways to inject beans in instances that are not created (managed) by Spring:
(1) add
@Configurable
annotation to this class - this requires real AspectJ (compile-time or load-time -weaving)- @see Spring Reference Chapter 7.8.1 Using AspectJ to dependency inject domain objects with Spring
- @see this answer of mine https://stackoverflow.com/a/7007572/280244 for a quick "guide" to enable the
@Configurable
support
(2) invoke
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
- @see this question and its (two highes voted answers) for some ideas how to use
You can only @Autowire a bean managed by Spring. So you have to declare your instance through some configuration : a bean in an xml file, or a @Bean method in a java configuration.
@Component are just automatically discovered and registered in the spring context.

- 10,611
- 1
- 26
- 43
-
I though the question was how to inject some external instance (from external bean) to a spring bean through @Autowire. Your answer are on how to inject spring bean to unmanaged external instance, the opposite ;-) – Jérémie B Feb 07 '16 at 18:10