有时候我们会发现我们通过 @autowired 注解注入为 null,此时我们就要手动注入了。我们可以写一个手动注入工具类,如下:
工具类:
package com.tiger.Utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanUtils implements ApplicationContextAware {
protected static ApplicationContext applicationContext ;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
if (applicationContext == null) {
applicationContext = arg0;
}
}
public static Object getBean(String name) {
//name表示其他要注入的注解name名
return applicationContext.getBean(name);
}
/**
* 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
使用:
原本的自动注入是这样写的
@Autowried
private RedisUtils redisUtil;
手动注入是这样写的
private RedisUtils redisUtil = BeanUtils.getBean(RedisUtils.class);
完美解决...