SpringContextUtlis工具类(通过bean的名字来获取有效的bean)
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class SpringContextUtils implements ApplicationContextAware {
public SpringContextUtils() {
// TODO Auto-generated constructor stub
}
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void createContext() {
applicationContext = new ClassPathXmlApplicationContext("spring-mvc.xml");
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
if (applicationContext == null){
return null;
}
return (T)applicationContext.getBean(name);
}
}
在相应的spring-*.xml文件中手动写bean
<!-- Service调用Dao --> <bean id="systemAction" class="com.cn.xt.system.SystemAction"> <property name="systemMapper" ref="systemMapper"/> </bean>
<!-- Dao调用sqlSessionFactory --> <bean id="systemMapper" class="com.cn.xt.daoImpl.systemMapperImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>