gpt4 book ai didi

java - Spring中Guice Provider的等价性

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:17 24 4
gpt4 key购买 nike

Spring中Guice的Provider等价于什么?

这是我需要用 Spring 替换的 Guice 代码:

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);
}

}

这里定义了绑定(bind):

public class MyModule implements Module {

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

}

最后,我的目标是对代理对象使用@Autowired,如下所示:

public class ConnectionTest {

@Autowired
MyProxy proxy;
}

另请注意,外部 jar 文件中的 MyProxy 类无法修改。

最佳答案

相当于 guice 的 ProviderFactoryBean在 Spring 。

来自文档:

The FactoryBean interface is a point of pluggability into the Spring IoC container's instantiation logic. If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your custom FactoryBean into the container.

示例

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;
}

}

当您有外部库和复杂的对象创建时,这是一种很好的方法,可以避免使用冗长的 XML 配置来设置 bean。

为了在您的上下文中使用它,您可以在上下文 XML 中将其作为普通 bean 提供,例如:

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

但是,如果您的 bean 很容易实例化(没有很多依赖项),您可以直接在上下文 XML 上设置它,例如:

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

备选

如果您使用 Spring 3,您可以编写一个配置类(用 @Configuration 注释的类),如文档所述here .使用这种方法,您可以执行以下操作:

@Configuration
public class MyConfiguration {

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

}

这会将您的实例添加到 spring 上下文中,并让它在其他类中 Autowiring 。但是需要进行一些配置,按照提供的文档进行操作非常容易。

关于java - Spring中Guice Provider的等价性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16433623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com