一: 注入一个 testutils 类
пакет com.shop.sell.utils; Импорт com.shop.sell.dto.cartdto; Импорт org.springframework.context.annotation.bean; Импорт org.springframework.context.annotation.configuration; @Configuration public class testutils {@bean (name = "testdemo") public cartdto shod () {cartdto cartdto = new cartdto (); cartdto.setproductid (789); cartdto.setproductquantity (10); вернуть Cartdto; }}二: 创建一个获取 Bean 的公 的公 类
пакет com.shop.sell.utils; Импорт org.springframework.beans.beansexception; Импорт org.springframework.context.applicationContext; Import org.springframework.context.applicationContextAware; Import org.springframework.stereotype.component; @Component public Class Springutil реализует ApplicationContextaware {private Static ApplicationContext ApplicationContext; @Override public 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 (название строки, класс <t> clazz) {return getApplicationContext (). getBean (имя, clazz); }}三: 在控制器中获取 фасоль 测试结果
пакет com.shop.sell.controller; импорт com.shop.sell.utils.resultvoutil; Импорт com.shop.sell.utils.springutil; Импорт com.shop.sell.vo.productinfovo; Импорт com.shop.sell.vo.productvo; импорт com.shop.sell.vo.resultvo; Импорт com.shop.sell.dataobject.productcategory; импорт com.shop.sell.dataobject.productinfo; Импорт com.shop.sell.dto.cartdto; Импорт com.shop.sell.from.orderform; Импорт com.shop.sell.service.categoryservice; Импорт com.shop.sell.service.productservice; Импорт org.springframework.beans.beanutils; Импорт org.springframework.beans.factory.annotation.autowired; Импорт org.springframework.context.applicationContext; Импорт org.springframework.web.bind.annotation.getMaping; Импорт org.springframework.web.bind.annotation.requestmapping; Импорт org.springframework.web.bind.annotation.restcontroller; импортировать java.util.arraylist; импортировать java.util.arrays; импортировать java.util.list; /** * 买家商品 */@RestController @Requestmapping ("/buyer/product") открытый класс BuyerProductController {private Static ApplicationContext ApplicationContext; @Autowired productservice productservice; @Autowired Private CategoryService CategoryService; @Getmapping (value = "/list") public cartdto list () {cartdto cartdto = (cartdto) springutil.getbean ("testdemo"); вернуть Cartdto; }}四: 使用 почтальон 测试结果
总结
以上所述是小编给大家介绍的关于 Springboot 获取 ioc 容器中注入的 Bean (推荐) , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!