- 1.背景:
- 2.原代码:
- 非spring环境中获取bean
项目在nio监听端口的事件中需要在接收到客户端数据以后把数据封装然后调用service层间接访问数据库插入数据,调试了一天,明明用了autowired但是仍然显示该service对象为空,一下是报错的代码:
@Component
public class Myselect implements Callable {
@Autowired
private WashService washService;
public void getSelector() throws IOException {
//创建 Selector
Selector selector = Selector.open();//用open方法创建
ServerSocketChannel channel = ServerSocketChannel.open();//获取通道
channel.configureBlocking(false);//切换为非阻塞模式
channel.bind(new InetSocketAddress(8004));
channel.register(selector, SelectionKey.OP_ACCEPT);//注册通道到选择器上,第二个参数为指定的事件为”监听接收事件“
//
// * 读 : SelectionKey.OP_READ (1)
/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware
{
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
SpringUtils.applicationContext = applicationContext;
}
@SuppressWarnings("unchecked")
public static T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
//例如 private static CacheManager cacheManager = SpringUtils.getBean(CacheManager.class);
}
public static T getBean(Class clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
public static Class> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
@SuppressWarnings("unchecked")
public static T getAopProxy(T invoker)
{
return (T) AopContext.currentProxy();
}
public static String[] getActiveProfiles()
{
return applicationContext.getEnvironment().getActiveProfiles();
}
public static String getActiveProfile()
{
final String[] activeProfiles = getActiveProfiles();
return StringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
}
}
然后修改刚刚的nio程序,注释掉autowired
加上:
WashService washService = SpringUtils.getBean("washservice");
washService.allWash().stream().forEach(System.out::println);
再次运行结果:
可见此时已经在这个nio服务端类中获得了washservice了。



