一:注入一個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”)public cartdto Said(){cartdto cartdto = new cartdto(); cartdto.setproductid(789); cartdto.setproductuctity(10);返回cartdto; }}}二:創建一個獲取bean的公共類
包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 {私有靜態應用程序Context ApplicationContext; @Override public void setapplicationContext(applicationContextContext)拋出beanSexception {if(springutil.applicationContext == null){springutil.applicationContext = applicationContext; }} public static applicationContext getApplicationContext(){return applicationContext; } public static對象getBean(string name){return get getApplicationContext()。 getBean(name); } public static <t> t getBean(class <t> clazz){return getapplicationContext()。 getBean(clazz); } public static <t> t getBean(string name,class <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(“/pareer/product”)public Class fublic Class fulerProductController {private static applicationContextContextContextContext; @Autowired私人產品服務產品服務; @Autowired私人類別服務類別服務; @getMapping(value =“/list”)public cartdto list(){cartdto cartdto =(cartdto)springutil.getBean(“ testDemo”);返回cartdto; }}}四:使用郵遞員測試結果
總結
以上所述是小編給大家介紹的關於springboot獲取ioc容器中註入的bean(推薦),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!