【SpringBoot】工具类手动获取bean和配置的方法

众所周知,springboot中,一般通过自动注入即可获取到bean或配置,但在一些场景,没办法注入的时候,比如说抽象类设置属性。

 1 @Slf4j
 2 public abstract class BaseController {
 3     private String secureKey = null;
 4     private String saltKey = null;
 5 
 6     /**
 7      * *****
 8      method
 9      * *****
10      */
11 }

此处,需要为secureKey和saltKey注入进配置的内容

1 data.encryption.secureKey=fdssadsadwqdsdsacaadfsafdsadas
2 data.sign.saltKey=we21rfcxzcdas

 

怎么办呢?于是就手写了工具类:

 1 @SuppressWarnings("unchecked")
 2 @Component
 3 public class SpringUtils implements ApplicationContextAware {
 4 
 5     private static ApplicationContext applicationContext;
 6     
 7     private static Environment env;
 8     
 9     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
10         SpringUtils.applicationContext = applicationContext;
11     }
12 
13     public static <T> T getBean(String beanName) {
14         if (applicationContext.containsBean(beanName)) {
15             return (T) applicationContext.getBean(beanName);
16         } else {
17             return null;
18         }
19     }
20 
21     public static <T> Map<String, T> getBeansOfType(Class<T> baseType) {
22         return applicationContext.getBeansOfType(baseType);
23     }
24     
25     public static String readConfig(String key) {
26         if(env == null) {
27             env = SpringUtils.getBeansOfType(Environment.class).get("environment");
28         }
29          return env.getProperty(key);
30     }
31 }

 

工具类实现ApplicationContextAware接口,重写setApplicationContext方法,注意类上的 @Component

应用启动时,spring将applicationContext对象通过setApplicationContext方法注入给静态的全局私有对象applicationContext

此时,即可使用静态方法,通过调用applicationContext的getBean来获取我们想要的bean

 

获取配置呢?配置一般通过Environment对象手动获取,Environmen对象没办法注入进来,所以readConfig方法中,读取配置前,通过单例模式从上面的getBean方法中获取Environmen,放入静态变量中。

这样既可通过SpringUntil的静态方法读取bean和配置

 1 @Slf4j
 2 public abstract class BaseController {
 3     private String secureKey = null;
 4     private String getSecureKey() {
 5         if(secureKey == null) {
 6             secureKey = SpringUtils.readConfig("data.encryption.secureKey");
 7         }
 8         return secureKey;
 9     }
10     private String saltKey = null;
11     private String getSaltKey() {
12         if(saltKey == null) {
13             saltKey = SpringUtils.readConfig("data.sign.saltKey");
14         }
15         return saltKey;
16     }
17 
18     public static final String REDIS_KEY_REQUESTID = "SMSPAY_REQUESTID_stationAlipayBill_tradePay_";
19 
20     /**
21      * *****
22      method
23      * *****
24      */
25 }

 

posted @ 2021-03-11 17:15  平平无奇刘彦祖  阅读(674)  评论(0)    收藏  举报