Bạn có thể lấy một tham chiếu đến applicationContext từ khắp mọi nơi (kể cả phá hủy đóng bootstrap) sử dụng rằng đoạn mã:
def ctx = org.codehaus.groovy.grails.web.context.ServletContextHolder.servletContext.getAttribute(org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes.APPLICATION_CONTEXT);
Bắt một tham chiếu đến một bean là dễ dàng như ctx.beanName
.
Đây là một lớp util nhỏ (viết bằng Java) có thể đơn giản hóa nhiệm vụ này:
import org.springframework.context.ApplicationContext;
import org.codehaus.groovy.grails.web.context.ServletContextHolder;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
public class SpringUtil {
public static ApplicationContext getCtx() {
return getApplicationContext();
}
public static ApplicationContext getApplicationContext() {
return (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) getApplicationContext().getBean(beanName);
}
}
và một ví dụ:
def bean = SpringUtil.getBean("beanName")
Chúc mừng, Sigi
Nguồn
2009-03-05 11:24:40