springboot 静态方法中使用@Autowired注入配置和Bean

简介: springboot 静态方法中使用@Autowired注入配置和Bean

@Autowired

@Component
public class StructUtil {
    private static RestTemplate restTemplate;
  private static String API_KEY;
  // 通过重写set注入
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        StructUtil.restTemplate = restTemplate;
    }
    @Value("${tripartite.setting.apiKey}")
    public void setApiKey(String apiKey) {
        StructUtil.API_KEY = apiKey;
    }
    public static void getStruct(){
      System.out.println(API_KEY);
      System.out.println(restTemplate);
    }
}

@PostConstruct注入


在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。

@Component
public class WeChatContant {
    @Autowired
    private RestTemplate restTemplate2;
    private static RestTemplate restTemplate;
    @PostConstruct
    public void init(){
        restTemplate= restTemplate2;
    }
    public static JSONObject doGerStr(String url){
       System.out.println(restTemplate);
       return null;
    }
}
相关文章
|
9天前
|
Java
springboot字段注入@value细节
springboot字段注入@value细节
12 1
|
9天前
|
Java
springboot自动注入避坑
springboot自动注入避坑
14 1
|
21小时前
|
文字识别 Java
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
|
1天前
|
Java 数据库连接 mybatis
SpringBoot配置Mybatis注意事项,mappers层下的name命名空间,要落实到Dao的video类,resultType要落到bean,配置好mybatis的对应依赖。
SpringBoot配置Mybatis注意事项,mappers层下的name命名空间,要落实到Dao的video类,resultType要落到bean,配置好mybatis的对应依赖。
|
1天前
|
Java
springboot 读取配置信息和对应bean
springboot 读取配置信息和对应bean
|
27天前
|
Java Spring
解决Springboot集成ElasticSearch 报错:A bean with that name has already been defined in null and overriding
解决Springboot集成ElasticSearch 报错:A bean with that name has already been defined in null and overriding
|
7天前
|
Java Linux 程序员
技术笔记:Spring生态研习【五】:Springboot中bean的条件注入
技术笔记:Spring生态研习【五】:Springboot中bean的条件注入
|
9天前
|
Java
手写SpringBoot(四)之bean动态加载
可以看到只有userApplication tomcatWebServer init打印,没有mySpringboot tomcatWebServer init打印,证明spring-boot只加载了用户定义的那个tomcatWebServer
8 0
|
13天前
|
Java
springboot Test 测试类中如何排除一个bean类
springboot Test 测试类中如何排除一个bean类
12 0
|
开发框架 Java Spring
Springboot @Autowired 和 @Resource 我的剖析,你看完就不会忘
Springboot @Autowired 和 @Resource 我的剖析,你看完就不会忘
400 0
Springboot @Autowired 和 @Resource 我的剖析,你看完就不会忘