代码如下
定义一个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());
}
}
网友评论