Guice Provider Equivalence in Spring

What is the equivalence of Guice Provider in Spring?

Here is the Guice code that I need to replace with Spring:

public class MyProxyProvider implements Provider<MyProxy> { @Inject Config config; @Override public MyProxy get() { return new MyProxy(httpsclient, config.server, config.user, config.password, config.version); } 

}

and here the binding is defined:

 public class MyModule implements Module { @Override public void configure(Binder g) { g.bind(MyProxy.class).toProvider(MyProxyProvider.class); } 

}

Finally, my goal is to use @Autowired for a proxy object as follows:

 public class ConnectionTest { @Autowired MyProxy proxy; 

}

Also note that the MyProxy class is in an external jar file that cannot be changed.

+4
source share
2 answers

Equivalent to Provider of guice - FactoryBean in Spring.

From the documentation:

The FactoryBean interface is the capacity point in the Spring Logic of IoC container creation. If you have complex initialization code that is better expressed in Java rather than a (potentially) verbose amount of XML, you can create your own FactoryBean, write complex initialization inside this class, and then connect your custom FactoryBean to the container.

Example

 public class MyFactoryBean implements FactoryBean<MyClassInterface> { @Override public MyClassInterface getObject() throws Exception { return new MyClassImplementation(); } @Override public Class<?> getObjectType() { return MyClassInterface.class; } @Override public boolean isSingleton() { return true; } } 

This is a good approach when you have external libraries and complex object creation to avoid a long XML configuration for setting beans.

To use it in your context, you can simply present it as a regular bean in your XML context, for example:

 ... <bean id="myClass" class="foo.bar.MyFactoryBean" /> ... 

BUT , if your bean is simple enough to instantiate (not many dependencies), you can configure it directly in the XML context, for example:

 <bean id="myClass" class="foo.bar.MyClassImplementation" /> 

Alternative

If you are using Spring 3, you can write a configuration class (a class annotated with @Configuration ) as described here . With this approach, you can do something like:

 @Configuration public class MyConfiguration { @Bean public MyClassInterface getMyClass() { return new MyClassImplementation(); } } 

This will add your instance to the Spring context and allow it to auto-invert to other classes. But some configuration is required, and it is quite easy according to the provided documentation.

+6
source

You are not using a provider in spring, but configure your MyProxy class as a stereotype. This can be done by annotating the class with @Component or @Service or another stereotype. And enable component checking for your package or it can be configured as a stereotype in applicationContext.xml

0
source

Source: https://habr.com/ru/post/1479676/


All Articles