环境:spring boot2.X + netty
在spring boot2.X架构中,在@Controller或者@Service注解下的类,可以通过依赖注入@Autowired,引入被@Service、@Component、@Configuration注解等被spring管理的bean对象,那么想在netty的主要功能Handler中引入操作数据库
的Dao层或者逻辑功能的Service层,怎么注入呢?
通过Spring的ApplicationContext进行spring上下文的管理,获取被spring管理的bean对象。
通过SpringUtils类进行获取被spring管理的bean对象。
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtils.applicationContext == null){
SpringUtils.applicationContext = applicationContext;
}
}
// 获取applicationContext
public static ApplicationContext getApplicationContext(){return applicationContext;}
// 通过name获取Bean
public static Object getBean(String name){ return getApplicationContext().getBean(name);}
// 通过class获取Bean
public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz);}
// 通过name, 以及clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz){ return getApplicationContext().getBean(name, clazz);}
}
使用时:
即可获取被spring管理的bean对象,进行其他逻辑功能的实现,操作Dao或者Service。OK。