一:注入一个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(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!