一: 注入一个 Testutils 类
Paket 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); return cartdto; }}二: 创建一个获取 Bean 的公 的公 类
Paket com.shop.sell.utils; import org.springframework.beans.beansexception; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextaware; import org.springframework.stereotype.comPonent; @Component Public Class Springutil implementiert ApplicationContextaware {private static applicationContext applicationContext; @Override public void setApplicationContext (ApplicationContext applicationContext) löst beansexception {if (springutil.applicationContext == null) {Springutil.applicationContext = ApplicationContext; }} public static applicationContext getApplicationContext () {return applicationContext; } öffentliches statisches Objekt getBean (String -Name) {return getApplicationContext (). getBean (Name); } public static <t> T getBean (Klasse <T> clazz) {return getApplicationContext (). getBean (Clazz); } public static <t> T getBean (String -Name, Klasse <T> clazz) {return getApplicationContext (). getBean (Name, Clazz); }}三: 在控制器中获取 Bean 测试结果
Paket 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; import 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; importieren java.util.list; /** * 买家商品 */@restController @RequestMapPing ("/käufer/produkt") öffentliche Klasse Käuferproduktcontroller {private statische AnwendungContext ApplicationContext; @Autowired Private Productsservice ProductService; @Autowired Private CategoryService CategoryService; @GetMapping (value = "/list") public cartdto list () {cartdto cartdto = (cartdto) springutil.getBean ("testDemo"); return cartdto; }}四: 使用 Postman 测试结果
总结
以上所述是小编给大家介绍的关于 Springboot 获取 ioc 容器中注入的 Bean (推荐) , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!