一: 注入一个 Testutils 类
paket com.shop.sell.utils; impor com.shop.sell.dto.cartdto; impor org.springframework.context.annotation.bean; impor org.springframework.context.annotation.configuration; @Configuration Public Class Testutils {@bean (name = "testDemo") cartdto umum mengatakan () {cartdto cartdto = cartdto baru (); cartdto.setproductid (789); cartdto.setProductQuantity (10); mengembalikan cartdto; }}二: 创建一个获取 bean 的公的公 类
paket com.shop.sell.utils; impor org.springframework.beans.beansException; impor org.springframework.context.applicationContext; impor org.springframework.context.applicationContextAware; impor org.springframework.stereotype.component; @Component Public Class Springutil mengimplementasikan ApplicationContextAware {private static applicationContext applicationContext; @Override public void setApplicationContext (ApplicationContext ApplicationContext) melempar beansException {if (springutil.applicationContext == null) {springutil.applicationContext = applicationContext; }} public static applicationContext getApplicationContext () {return applicationContext; } objek statis public getBean (nama string) {return getApplicationContext (). getBean (name); } public static <T> t getBean (class <T> clazz) {return getApplicationContext (). getBean (clazz); } public static <T> t getBean (nama string, kelas <t> clazz) {return getApplicationContext (). getBean (name, clazz); }}三: 在控制器中获取 Bean 测试结果
paket com.shop.sell.controller; impor com.shop.sell.utils.resultvoutil; impor com.shop.sell.utils.springutil; impor com.shop.sell.vo.productinfovo; impor com.shop.sell.vo.productvo; impor com.shop.sell.vo.resultvo; impor com.shop.sell.dataobject.productcategory; impor com.shop.sell.dataobject.productInfo; impor com.shop.sell.dto.cartdto; impor com.shop.sell.from.orderform; impor com.shop.sell.service.categoryservice; impor com.shop.sell.service.productservice; impor org.springframework.beans.beanutils; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.context.applicationContext; impor org.springframework.web.bind.annotation.getmapping; impor org.springframework.web.bind.annotation.requestmapping; impor org.springframework.web.bind.annotation.RestController; impor java.util.arraylist; impor java.util.arrays; impor java.util.list; /** * 买家商品 */@RestController @RequestMapping ("/pembeli/produk") Pembeli kelas publik PEMBELIRUCTCROLLER {private static applicationContext ApplicationContext; @Autowired private productservice productservice; @Autowired Private CategoryService CategoryService; @GetMapping (value = "/list") Public cartDTO list () {cartdto cartdto = (cartdto) springutil.getBean ("testdemo"); mengembalikan cartdto; }}四: 使用 tukang pos 测试结果
总结
以上所述是小编给大家介绍的关于 Springboot 获取 IOC 容器中注入的 kacang (推荐) , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!