美文网首页
利用BeanFactoryAware获取spring容器中的对象

利用BeanFactoryAware获取spring容器中的对象

作者: 大风过岗 | 来源:发表于2020-12-31 15:24 被阅读0次

代码如下

定义一个GetSpringBeanAware


/**
 * @Author: chihaojie
 * @Date: 2020/12/31 15:12
 * @Version 1.0
 * @Note
 */
@Component
public class GetSpringBeanAware implements BeanFactoryAware {


    private BeanFactory factory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        factory = beanFactory;
    }


    /**
     * 获取spring容器中的对象
     *
     * @return
     */
    public Object getBean(){
      return   factory.getBean("kafkaSender");
    }
}


获取spring容器中的对象

/**
 * @Author: chihaojie
 * @Date: 2020/9/24 15:45
 * @Version 1.0
 * @Note
 */
@Slf4j
@Api(value = "测试API")
@RestController
public class TestKafkaController {


    @Autowired
    private GetSpringBeanAware  getSpringBeanAware;

    @Autowired
    private KafkaService  kafkaService;

    /**
     * 模拟消息发送
     */
    @ApiOperation(value = "模拟消息发送", httpMethod = "GET", notes = "模拟消息发送")
    @RequestMapping(value = "/kafka/msgSend",method= RequestMethod.GET)
    public void msgSend(@RequestParam("topic") String topic, @RequestParam("value") String value)throws Exception {
        //kafkaService.send(topic,value);
        KafkaSender sender = (KafkaSender) getSpringBeanAware.getBean();
        System.out.println("获取到springBean");
        sender.sendMessage("test-tstt","hhhh");
    }

    @ApiOperation(value = "mvc", httpMethod = "GET", notes = "mvc")
    @RequestMapping(value = "/mvc/test",method= RequestMethod.GET)
    public Result<Object> mvctest(@RequestParam("topic") String topic, @RequestParam("value") String value)throws Exception {
        return new Result<>().ok(new Date());
    }

}

相关文章

网友评论

      本文标题:利用BeanFactoryAware获取spring容器中的对象

      本文链接:https://www.haomeiwen.com/subject/jbtroktx.html