user1340582
user1340582

Reputation: 19729

Possible to autowire imported utility classes in Spring?

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?

Upvotes: 0

Views: 19136

Answers (2)

Ralph
Ralph

Reputation: 120851

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:

Upvotes: 3

J&#233;r&#233;mie B
J&#233;r&#233;mie B

Reputation: 11022

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.

Upvotes: 2

Related Questions