我创建了一个jar,其中包含RestTemplate的配置。例如,
java-客户端jar:
com.java.rest.client
@Configuration
public class RestTemplateClient {
public RestTemplateClient() {
}
@Bean(
name = {"restClient"}
)
RestTemplate restTemplate() throws Exception {
//HTTP configurations
}
}
我正在另一个spring启动应用程序中使用这个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的新手,有人能给我介绍一下吗?
发布于 2021-04-19 19:35:36
要做到这一点,最好的方法是使用spring.factories
机制。
在spring boot documentation中阅读有关它的更多信息
如果您有一个应该由spring boot项目自动加载的配置,那么可以在java-client
模块中创建一个文件:src/main/resources/META-INF/spring.factories
。
在spring boot应用程序启动期间,spring boot会查找spring.factories
文件并加载其中指定的配置。
该文件是一个属性文件,您可以在其中指定不同的内容,在这种情况下,您应该放置如下内容:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yourorg.yourproject.RestTemplateClient
您应该将rest-client模块视为任何其他依赖项,在maven/gradle中定义它,等等。
https://stackoverflow.com/questions/67160797
复制相似问题