一: 注入一个 TestUtils 类
حزمة com.shop.sell.utils ؛ استيراد com.shop.sell.dto.cartdto ؛ استيراد org.springframework.context.annotation.bean ؛ استيراد org.springframework.context.annotation.configuration ؛ Configuration الفئة العامة TestUtils {bean (name = "testDemo") saids public cartdto () {cartdto cartdto = new cartdto () ؛ cartdto.setproductid (789) ؛ cartdto.setProductquantity (10) ؛ العودة cartdto }}二: 创建一个获取 الفول 的公 类
حزمة com.shop.sell.utils ؛ استيراد org.springframework.beans.beansexception ؛ استيراد org.springframework.context.applicationContext ؛ استيراد org.springframework.context.applicationContextAware ؛ استيراد org.springframework.stereotype.component ؛ Component Public Class SpringUtil تنفذ ApplicationContextAware {private static applicationContext ApplicationContext ؛ Override public void setapplicationContext (applicationContext ApplicationContext) يلقي beansexception {if (springutil.applicationContext == null) {springutil.applicationContext = applicationContext ؛ }} application application applicationcontext getapplicationContext () {return applicationContext ؛ } الكائن الثابت العام getBean (اسم السلسلة) {return getApplicationContext (). getBean (name) ؛ } static public <T> t getBean (class <T> clazz) {return getApplicationContext (). getBean (clazz) ؛ } static public <T> t getBean (اسم السلسلة ، الفئة <T> clazz) {return getApplicationContext (). getBean (name ، 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.getMapping ؛ استيراد org.springframework.web.bind.annotation.requestmapping ؛ استيراد org.springframework.web.bind.annotation.restController ؛ استيراد java.util.arraylist ؛ استيراد java.util.arrays ؛ استيراد java.util.list ؛ /** * 买家商品 */ @RestController @REquestMapping ("/المشتري/المنتج") فئة عامة المشتري {private static applicationContext ApplicationContext ؛ Autowired Private Productervice ProductService ؛ Autowired Private CatevoryService Service ؛ getMapping (value = "/list") قائمة cartdto العامة () {cartdto cartdto = (cartdto) springutil.getBean ("testDemo") ؛ العودة cartdto }}四: 使用 Postman 测试结果
总结
以上所述是小编给大家介绍的关于 Springboot 获取 IOC 容器中注入的 Bean (推荐) , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!