1. บริบทที่จัดทำโดยฤดูใบไม้ผลิ
WebApplicationContext WAC = contextloader.getCurrentWebapplicationContext (); wac.getBean (beanid);
วิธีนี้ไม่ได้ขึ้นอยู่กับ servlets และไม่จำเป็นต้องฉีด อย่างไรก็ตามควรสังเกตว่าเมื่อเซิร์ฟเวอร์เริ่มต้นและคอนเทนเนอร์สปริงเริ่มต้น
2. ใช้อินเทอร์เฟซ ApplicationContextaware
กำหนดคลาสเครื่องมือ
คลาสสาธารณะ SpringContextUtil ใช้ ApplicationContextAware {Private application applicationcontext applicationContext; // สปริงแอปพลิเคชันบริบทสภาพแวดล้อม/** * ใช้วิธีการโทรกลับของอินเตอร์เฟส ApplicationContextAware และตั้งค่าสภาพแวดล้อมบริบท * @param application * @throws beansexception */โมฆะสาธารณะ setapplicationContext (applicationcontext applicationcontext) โยน beansexception } / ** * @return ApplicationContext * / Public Static ApplicationContext GetApplicationContext () {return ApplicationContext; } / *** รับวัตถุ* @param ชื่อ* @return Object อินสแตนซ์ของถั่วที่ลงทะเบียนด้วยชื่อที่กำหนด* @throws beansexception* / วัตถุคงที่สาธารณะ getBean (ชื่อสตริง) โยน beansexception {return applicationcontext.getBean (ชื่อ); } / ** * รับวัตถุประเภทที่ต้องการ type * หากถั่วไม่สามารถแปลงตามประเภทได้ข้อยกเว้นที่สอดคล้องกันจะถูกโยน (beannotofrequiredTypeException) * @param ชื่อชื่อการลงทะเบียนถั่ว beansexception {return applicationcontext.getBean (ชื่อ, ต้องการ type); } / ** * หาก beanfactory มีคำจำกัดความถั่วที่ตรงกับชื่อที่กำหนดให้กลับมาจริง * @param ชื่อ * @return boolean * / public public boolean containsbean (ชื่อสตริง) {return applicationcontext.containsbean (ชื่อ); } /*** พิจารณาว่าคำจำกัดความของถั่วที่ลงทะเบียนด้วยชื่อที่กำหนดนั้นเป็นซิงเกิลหรือต้นแบบ * หากไม่พบคำจำกัดความของถั่วที่สอดคล้องกับชื่อที่กำหนดจะมีข้อยกเว้นจะถูกโยนลง (nosuchbeanDefinitionException) * @param ชื่อ * @return บูลีน * @throws nosuchbeandefinitionexception */ public boolean issingleton (ชื่อสตริง) } / ** * @param name * @return class ประเภทของวัตถุที่ลงทะเบียน * @throws nosuchbeanDefinitionException * / คลาสคงที่คลาสคงที่ getType (ชื่อสตริง) โยน nosuchbeanDefinitionException {return ApplicationContext.getType (ชื่อ); } / ** * หากชื่อถั่วที่กำหนดมีนามแฝงในคำจำกัดความของถั่วนามแฝงเหล่านี้จะถูกส่งคืน * @param ชื่อ * @return * @throws nosuchbeanDefinitionException * / สตริงคงที่สาธารณะ [] getaliases (ชื่อสตริง) -3. กำหนดค่าถั่ว
<!-SpringContextUtil รับถั่วผ่านรหัส-> <bean id = "SpringContextUtil"/>>>>>
สรุป
ข้างต้นมีหลายวิธีที่สปริงได้รับถั่วในรหัส ฉันหวังว่าเนื้อหาของบทความนี้จะเป็นประโยชน์ต่อการศึกษาหรือที่ทำงานของทุกคน หากคุณมีคำถามใด ๆ คุณสามารถฝากข้อความไว้เพื่อสื่อสาร