-
背景说明
当前的springboot项目依赖第三提供的jar,其中用到一个类想通过spring容器进行管理(创建Bean实例的过程交给spring容器),在用到该类的地方通过依赖注入的方式注入即可 -
针对以上的需求,通过亲自实践总结了如下三种方式
方式一:通过@Bean构建Bean的方式将jar中的类添加到spring容器中
1.1在项目的config目录下,添加配置类,配置类必须加上@Configuration注解,告诉spring这是配置类
package cn.shanxincd.ih.supervise.config;
import cn.shanxincd.ih.supervise.dto.OrgConfigDTO;
import cn.shanxincd.ih.supervise.entity.OrgConfig;
import cn.shanxincd.ih.supervise.service.OrgConfigService;
import lombok.extern.slf4j.Slf4j;
import ngari.openapi.updateInterface.Securitykey;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author yangfeng
* @version 1.0
* @date 2022-09-28 17:34
*/
@Configuration
@Slf4j
public class SecuritykeyConfig {
@Value("${postinfo.apiUrl}")
private String apiUrl;
@Value("${postinfo.serviceId}")
private String serviceId;
private final OrgConfigService orgConfigService;
public SecuritykeyConfig(OrgConfigService orgConfigService) {
this.orgConfigService = orgConfigService;
}
@Bean
public Securitykey securitykey(){
Securitykey securitykey = new Securitykey();
securitykey.setApiUrl(apiUrl);//设置请求的路径信息
securitykey.setServiceId(serviceId);
OrgConfigDTO orgConfig = orgConfigService.getOrgConfig();
if(null!=orgConfig){
BeanUtils.copyProperties(orgConfig,securitykey);
}
log.info("请求路径==={} appKey==={}",securitykey.getApiUrl(),securitykey.getAppKey());
return securitykey;
}
}
然后在使用到该类的地方用@Autowired或者@Resource
方式二:通过在启动类中使用@Import注解
方式三:通过在spring.factories中加入需要注册的Bean的全类名,告诉spring容器这是需要管理注册的bean
3.1在resource目录下创建META-INF目录,然后在META-INF目录下创建spring.factories文件,在该文件下添加内容
# 自动添加以下类到spring容器中,以下类为项目依赖jar中的类或者不是Application所在包下面的类即可通过这种方式注册到spring容器中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
ngari.openapi.updateInterface.Securitykey
这样spring项目在启动时就能扫描到该类并添加到spring容器中