首页 > 解决方案 > 创建在外部 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的新手,有人可以指导吗?

标签: javaspring-bootresttemplate

解决方案


IMO 最好的方法是使用spring.factories机制。

在Spring Boot 文档中阅读有关它的更多信息

如果你有一个配置应该由 spring boot 项目自动加载,你可以创建一个文件:src/main/resources/META-INF/spring.factoriesjava-client模块中。

在 spring boot 应用程序启动期间,spring boot 会查找spring.factories文件并加载那里指定的配置。

该文件是一个属性文件,您可以在其中指定不同的内容,在这种情况下,您应该放置以下内容:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yourorg.yourproject.RestTemplateClient

您应该将 rest-client 模块视为任何其他依赖项,在 maven/gradle 等中定义它。


推荐阅读