0

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?

user1340582
  • 18,359
  • 34
  • 109
  • 165

2 Answers2

3

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:

Community
  • 1
  • 1
Ralph
  • 115,440
  • 53
  • 279
  • 370
2

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.

Jérémie B
  • 10,129
  • 1
  • 23
  • 39
  • 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