一: 注入一个 Testutils 类
package com.shop.sell.utils; import com.shop.sell.dto.cartdto; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; @Configuration Public Class TestUtils {@Bean (name = "TestDemo") public CartdTo Said () {Cartdto Cartdto = new CartdTo (); cartdto.setProductId (789); cartdto.setproductquantity (10); retour cartdto; }}二: 创建一个获取 Bean 的公 的公 类
package com.shop.sell.utils; import org.springframework.beans.beanSexception; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.sterereotype.Component; @Component public class SpringUtil implémente applicationContextAware {private static applicationContext applicationContext; @Override public void setApplicationContext (applicationContext ApplicationContext) lève BeanSException {if (springUtil.ApplicationContext == null) {SpringUtil.ApplicationContext = applicationContext; }} public static applicationContext getApplicationContext () {return applicationContext; } objet statique public getBean (nom de chaîne) {return getApplicationContext (). getBean (name); } public static <t> t getbean (class <T> Clazz) {return getApplicationContext (). getbean (Clazz); } public static <t> t getbean (nom de chaîne, classe <T> Clazz) {return getApplicationContext (). getBean (name, Clazz); }}三: 在控制器中获取 Bean 测试结果
package com.shop.sell.Controller; import com.shop.sell.utils.resultvoutil; import com.shop.sell.utils.springutil; import com.shop.sell.vo.productInfovo; import com.shop.sell.vo.productvo; import com.shop.sell.vo.resultvo; import com.shop.sell.dataObject.ProductCategory; import com.shop.sell.dataObject.productInfo; import com.shop.sell.dto.cartdto; Importer com.shop.sell.from.orderForm; import com.shop.sell.service.categoryService; import com.shop.sell.service.productService; import org.springframework.beans.beanutils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.getMapping; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restController; import java.util.arraylist; import java.util.arrays; Importer java.util.list; / ** * 买家商品 * / @RestController @RequestMapping ("/ Buyer / Product") Class public BuyerProductController {Private Static ApplicationContext ApplicationContext; @Autowired Private ProductService ProductService; @Autowired Private CatégoryService CatégoryService; @GetMapping (value = "/ list") public cartdto list () {cartdto cartdto = (cartdto) springUtil.getBean ("testdemo"); retour cartdto; }}四: 使用 Postman 测试结果
总结
以上所述是小编给大家介绍的关于 Springboot 获取 IOC 容器中注入的 Bean (推荐) , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!