首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建在外部jar弹簧引导中配置的bean

创建在外部jar弹簧引导中配置的bean
EN

Stack Overflow用户
提问于 2021-04-19 19:05:48
回答 1查看 49关注 0票数 1

我创建了一个jar,其中包含RestTemplate的配置。例如,

java-客户端jar:

com.java.rest.client

代码语言:javascript
运行
复制
@Configuration
public class RestTemplateClient {

public RestTemplateClient() {
}

@Bean(
    name = {"restClient"}
)
RestTemplate restTemplate() throws Exception {
    //HTTP configurations
}
}

我正在另一个spring启动应用程序中使用这个jar。我想使用jar中提供的相同restTemplate配置。但是在自动连接restTemplate时,它抛出了空指针异常。

在Sprint引导项目中..com.example.auth

代码语言:javascript
运行
复制
@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的新手,有人能给我介绍一下吗?

EN

回答 1

Stack Overflow用户

发布于 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文件并加载其中指定的配置。

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

代码语言:javascript
运行
复制
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yourorg.yourproject.RestTemplateClient

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67160797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档