一: 注入一个 testutils 类
paquete com.shop.sell.utils; import 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 Said () {CARTDTO CARTDTO = new CartDTO (); CARTDTO.SetProductid (789); CARTDTO.SetProductquantity (10); devolver CARTDTO; }}二: 创建一个获取 bean 的公 mas 类
paquete com.shop.sell.utils; importar org.springframework.beans.beansexception; importar org.springframework.context.applicationContext; importar org.springframework.context.applicationContextAware; importar org.springframework.stereotype.component; @Component public class SpringUtil Implements ApplicationContextAWee {private static applicationContext ApplicationContext; @Override public void setApplicationContext (ApplicationContext ApplicationContext) lanza Beansexception {if (SpringUtil.ApplicationContext == NULL) {SpringUtil.ApplicationContext = ApplicationContext; }} public static ApplicationContext getApplicationContext () {return ApplicationContext; } Public Static Object getBean (nombre de cadena) {return getApplicationContext (). getBean (nombre); } public static <t> t getBean (class <t> clazz) {return getApplicationContext (). getBean (clazz); } public static <t> t getBean (nombre de cadena, clase <t> clazz) {return getApplicationContext (). getBean (name, clazz); }}三: 在控制器中获取 Bean 测试结果
paquete 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; 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; import java.util.arrayList; importar java.util.arrays; import java.util.list; /** * 买家商品 */@RestController @RequestMapping ("/Buyer/Product") Public Class BuyerProductController {Private Static ApplicationContext ApplicationContext; @Autowired Productservice Productservice; @Autowired Categoría privada Categoría de servicio; @GetMapping (value = "/list") public Cartdto list () {CARTDTO CARTDTO = (CARTDTO) Springutil.getBean ("TestDemo"); devolver CARTDTO; }}四: 使用 Postman 测试结果
总结
以上所述是小编给大家介绍的关于 springboot 获取 容器中注入的 bean (推荐) , 希望对大家有所帮助 如果大家有任何疑问请给我留言 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持! 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!