某些时候,某些类是不归IOC管的,如我们的一些Util,如何使用IOC中的Bean?
1、写一个SpringUtil类,该类用于操纵Spring的ApplicationContext
@Component的注解是需要的,该Util是要被Spring管理的。
@Component public class SpringUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException{if (SpringUtil.applicationContext == null){SpringUtil.applicationContext = applicationContext;}}public static ApplicationContext getApplicationContext(){return applicationContext;}public static Object getBean(String name){return getApplicationContext().getBean(name);}public static <T> T getBean(Class<T> clazz){return getApplicationContext().getBean(clazz);}public static <T> T getBean(String name, Class<T> clazz){return getApplicationContext().getBean(name, clazz);} }
2、通过@Bean注解,返回一个Bean;
@Component @Transactional public class SysParamBusiness {@Autowiredprivate SysParamDao sysParamDao;public void modify(SysParamMO mo) throws LittleCatException{sysParamDao.modify(mo);}public String getValueByName(String name) throws LittleCatException{return sysParamDao.getValueByName(name).getValue();}public List<SysParamMO> getList() throws LittleCatException{return sysParamDao.getList();}@Bean(name="SysParamBusiness") public SysParamBusiness getSysParamBusiness(){return new SysParamBusiness();} }
3、在我们自己的Util中使用
public class SysParamUtil {public static String PARAM_NAME_MEMBER_ENABLE_DAYS = "member_enable_days";private static final SysParamBusiness sysParamBusiness = (SysParamBusiness) SpringUtil.getBean("SysParamBusiness");public static String getValueByName(String name) throws LittleCatException{return sysParamBusiness.getValueByName(name);} }
注:
也可以这样使用(如果没有特殊逻辑,推荐使用这种方法):
private static final SysParamBusiness sysParamBusiness = SpringUtil.getBean(SysParamBusiness.class);
这样,第二步就可以省略了。