一: 注入一个 testutils 类
pacote com.shop.sell.utils; importar com.shop.sell.dto.cartdto; importar org.springframework.context.annotation.bean; importar org.springframework.context.annotation.configuration; @Configuration public class Testutils {@Bean (name = "testDemo") public Cartdto disse () {Cartdto Cartdto = new Cartdto (); Cartdto.setProductId (789); Cartdto.SetProductQuantity (10); retornar Cartdto; }}二: 创建一个获取 Bean 的公 类 类
pacote com.shop.sell.utils; importar org.springframework.beans.beansception; importar org.springframework.context.ApplicationContext; importar org.springframework.context.applicationContexTAWe; importar org.springframework.tereotype.component; @Component Public Class Springutil implementa ApplicationContexTAWe {private estático ApplicationContext ApplicationContext; @Override public void setApplicationContext (ApplicationContext ApplicationContext) lança beansexception {if (springUtil.applicationContext == null) {springUtil.applicationContext = ApplicationContext; }} public static ApplicationContext getApplicationContext () {return ApplicationContext; } public static objeto getBean (nome da string) {return getApplicationContext (). getBean (nome); } public static <t> t getBean (classe <T> clazz) {return getApplicationContext (). getBean (clazz); } public static <t> t getbean (nome da string, classe <t> clazz) {return getApplicationContext (). getBean (nome, clazz); }}三: 在控制器中获取 Bean 测试结果
pacote com.shop.sell.Controller; importação com.shop.sell.utils.resultvoutil; importação com.shop.sell.utils.springutil; importar com.shop.sell.vo.productinfovo; importar com.shop.sell.vo.productvo; importar com.shop.sell.vo.resultvo; importar com.shop.sell.dataObject.productcategory; importação com.shop.sell.dataObject.productinfo; importar com.shop.sell.dto.cartdto; importar com.shop.sell.from.orderform; importar com.shop.sell.service.categoryservice; importar com.shop.sell.service.productService; importar org.springframework.beans.beanutils; importar org.springframework.beans.factory.annotation.autowired; importar org.springframework.context.ApplicationContext; importar org.springframework.web.bind.annotation.getMapping; importar org.springframework.web.bind.annotation.requestmapping; importar org.springframework.web.bind.annotation.restcontroller; importar java.util.arraylist; importar java.util.arrays; importar java.util.list; /** * 买家商品 */@restcontroller @ReQuestMapping ("/comprador/produto") public classe BuyerProductController {private estático ApplicationContext ApplicationContext; @Autowired PrivateService Products Service; @Autowired Private CategoryService CategoryService; @GetMapping (value = "/list") public Cartdto List () {Cartdto Cartdto = (Cartdto) SpringUtil.getBean ("testDemo"); retornar Cartdto; }}四: 使用 Postman 测试结果
总结
以上所述是小编给大家介绍的关于 Springboot 获取 ioc 容器中注入的 Bean (推荐) , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!