在我的 spring 托管组件中自动连接第三方库
Auto-wire third party library in my spring managed component
我在我的应用程序中使用第三方库来完成一些任务。他们提供了一个包装器,我使用 maven 在我的项目中添加了该包装器。为了使用这个包装器,我们必须给他们的客户一个访问密钥 class 才能使用它的功能。例如:
final WeatherApiService was = new WeatherApiServiceImpl(accessKey);
final WeatherApiClient weatherApiClient = new WeatherApiClient(was);
我想要的是删除上面的代码(因为它是一种单例,应该在应用程序启动时在 spring 上下文中注册)并做一些事情,这样我就可以自动装配 WeatherApiClient 和我们准备好了。 (包装器未使用 spring 仅供参考)。下面是我在 spring 上下文中所做的,我注册了两个 bean 并将访问密钥设置为 web.xml.
spring-context.xml
<bean id="was" class="my.librarypath.WeatherApiService ">
<constructor-arg type="java.lang.String" value="${accessKeyFromWebXml}"/>
</bean>
<bean id="weatherApiClient" class="my.librarypath.WeatherApiClient">
<constructor-arg type="my.librarypath.WeatherApiService" value="was"/>
</bean>
my component that will use the third party library
@Component("myComponent")
public class MyComponent IComponent {
@Resource(name = "weatherApiClient") // <--- getting Error here i.e: Couldn't aurtowire, bean should be of String type
private String weatherApiClient;
public void myFunction() {
weatherApiClient.getWeather();
}
}
有人可以确认我做的是否正确,或者是否有可用的最佳实践选项!?
有两个问题:
<bean id="weatherApiClient" class="my.librarypath.WeatherApiClient">
<constructor-arg type="my.librarypath.WeatherApiService" value="was"/>
// ^---- should be ref
</bean>
其次,我使用的是 String
而不是 WeatherApiClient
。我的坏处:/
@Resource(name = "weatherApiClient")
private String weatherApiClient;
// ^---- this one should have to be WeatherApiClient
我在我的应用程序中使用第三方库来完成一些任务。他们提供了一个包装器,我使用 maven 在我的项目中添加了该包装器。为了使用这个包装器,我们必须给他们的客户一个访问密钥 class 才能使用它的功能。例如:
final WeatherApiService was = new WeatherApiServiceImpl(accessKey);
final WeatherApiClient weatherApiClient = new WeatherApiClient(was);
我想要的是删除上面的代码(因为它是一种单例,应该在应用程序启动时在 spring 上下文中注册)并做一些事情,这样我就可以自动装配 WeatherApiClient 和我们准备好了。 (包装器未使用 spring 仅供参考)。下面是我在 spring 上下文中所做的,我注册了两个 bean 并将访问密钥设置为 web.xml.
spring-context.xml
<bean id="was" class="my.librarypath.WeatherApiService ">
<constructor-arg type="java.lang.String" value="${accessKeyFromWebXml}"/>
</bean>
<bean id="weatherApiClient" class="my.librarypath.WeatherApiClient">
<constructor-arg type="my.librarypath.WeatherApiService" value="was"/>
</bean>
my component that will use the third party library
@Component("myComponent")
public class MyComponent IComponent {
@Resource(name = "weatherApiClient") // <--- getting Error here i.e: Couldn't aurtowire, bean should be of String type
private String weatherApiClient;
public void myFunction() {
weatherApiClient.getWeather();
}
}
有人可以确认我做的是否正确,或者是否有可用的最佳实践选项!?
有两个问题:
<bean id="weatherApiClient" class="my.librarypath.WeatherApiClient">
<constructor-arg type="my.librarypath.WeatherApiService" value="was"/>
// ^---- should be ref
</bean>
其次,我使用的是 String
而不是 WeatherApiClient
。我的坏处:/
@Resource(name = "weatherApiClient")
private String weatherApiClient;
// ^---- this one should have to be WeatherApiClient