Spring一些问题记录

一、在非springbean中注入beanjava

        在项目中有时须要根据须要在本身new一个对象,或者在某些util方法或属性中获取Spring Bean对象,从而完成某些工做,可是因为本身new的对象和util方法并非受Spring所管理的,若是直接在所依赖的属性上使用@Autowired就会报没法注入的错误,或者是没报错,可是使用的时候会报空指针异常。总而言之因为其是不受IoC容器所管理的,于是没法注入。spring

        Spring提供了两个接口:BeanFactoryAware和ApplicationContextAware,这两个接口都继承自Aware接口。以下是这两个接口的声明:app

public class Startup implements ApplicationContextAware, ServletContextAware {

    private static Logger logger = Logger.getLogger(Startup.class);

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info(" service was setApplicationContext");
        this.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        Map<String, T> beans = applicationContext.getBeansOfType(clazz);
        return Lists.newArrayList(beans.values()).get(0);
    }

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

    在非springbean中能够经过静态方法 Startup .getBean()获取bean。ide

二、注入静态类变量工具

    是第一点问题的延伸,封装一些工具类的时候,并且当前工具类是一个spring的bean,工具类通常都是静态类型的,除了经过第一种方法注入bean外,能不能经过@AutoWire去注入呢,其实这个场景仍是有点问题的,竟然是工具类没有必要注册成为bean了吧,可是若是非要这么作的话,能够经过@PostConstruct  + @AutoWire的方式进行进行注入:this

@Component  
public class StaticUtils{  
    @Autowired  
    private static AaService service;  
  
    private static StaticUtils staticUtils; 

    @PostConstruct  
    public void init() {  
        staticUtils= this;  
        staticUtils.service= this.service; //把类变量赋值到实例变量上
    }  
  
}

还有一种办法是经过set方法进行注入:指针

@Component  
public class StaticUtil {  
  
    private static AaService service;  
      
    @Autowired  
    public void setService(AaService service) {  
        StaticUtil.service= service;  
    }  
}
相关文章
相关标签/搜索