一、在非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; } }