java - 创建在外部 jar spring boot 中配置的 bean
问题描述
我创建了一个具有 RestTemplate 配置的 jar。例如,
java客户端jar:
com.java.rest.client
@Configuration
public class RestTemplateClient {
public RestTemplateClient() {
}
@Bean(
name = {"restClient"}
)
RestTemplate restTemplate() throws Exception {
//HTTP configurations
}
}
我在另一个 spring boot 应用程序中使用这个 jar。我想使用 jar 中可用的相同 restTemplate 配置。但是在自动装配 restTemplate 时,它会抛出空指针异常。
在 Sprint 启动项目中.. com.example.auth
@Service
public class Auth {
@Autowired
@Qualifier("restClient")
RestTemplate restTemplate;
public void sampleMethod()
throws ResourceAccessException, Exception {
restTemplate.setErrorHandler(errorHandler); //throws NullPointerException
HttpHeaders headers = createHttpHeaders();
HttpEntity<T> entity = new HttpEntity<T>(data, headers);
restTemplate.exchange("url",
GET,
entity,
class);
}
}
我是Spring Boot的新手,有人可以指导吗?
解决方案
IMO 最好的方法是使用spring.factories
机制。
在Spring Boot 文档中阅读有关它的更多信息
如果你有一个配置应该由 spring boot 项目自动加载,你可以创建一个文件:src/main/resources/META-INF/spring.factories
在java-client
模块中。
在 spring boot 应用程序启动期间,spring boot 会查找spring.factories
文件并加载那里指定的配置。
该文件是一个属性文件,您可以在其中指定不同的内容,在这种情况下,您应该放置以下内容:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yourorg.yourproject.RestTemplateClient
您应该将 rest-client 模块视为任何其他依赖项,在 maven/gradle 等中定义它。
推荐阅读
- java - 如何从扫描仪读取文本文件并转换为 Int 数组 Java
- dictionary - 无法在 mapbox GL 上渲染矢量点
- javascript - 如何在 DT 单元格中使用 shinyjqui::orderInput
- angular - 单击 ion-back-button 将更改地址栏中的查询参数
- isometric - Godot 3.0 沿路径更改 KinimaticBody 2D 的动画
- mysql - 如何进行查询以在两列中添加值
- c++ - 声明与“Message::save(
&follow)” - twilio - 如何为未接听的电话设置操作?
- java - 使用 Connector/J 连接到 MYSQL
- c# - GDI+ 位图处理和无效参数错误