zl程序教程

您现在的位置是:首页 >  Python

当前栏目

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

2023-03-07 09:16:00 时间

@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;
    }
}