实现dubbo的Filter接口,如何注入spring容器里的bean

最近项目里用到dubbo的filter来做一些预处理的业务,但发现继承了Filter接口的类,无法通过@Autowired或者@Resource来注入spring容器里的对象,比如有个TestService,可以通过下面两种方式注入进来

1.dubbo通过setter方式自动注入

	private TestService testService;
	
	public void setTestService(TestService testService) {
		this.testService = testService;
	}

2.第二种,通过ApplicationContext的方式来获取

可以自己先实现一个SpringUtil实现ApplicationContextAware接口,如下

@Component
public class SpringUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringUtil.applicationContext == null) {
			SpringUtil.applicationContext = applicationContext;
		}
	}

	// 获取applicationContext
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	// 通过name获取 Bean.
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

}

然后调用这个工具类来获取对象

TestService testService = (TestService) SpringUtil.getBean("testService");

 

你可能感兴趣的:(dubbo)