SpringBoot在普通类使用service

1、在启动类里面,给需要用到service的类传入上下文。
@SpringBootApplication
public class ChatsystemApplication {

public static void main(String[] args) {

    ConfigurableApplicationContext configurableApplicationContext =  SpringApplication.run(ChatsystemApplication.class, args);
    WebSocketServer.setApplicationContext(configurableApplicationContext);
}

2、装入上下文

public class WebSocketServer {

//此处是解决无法注入的关键
private static ApplicationContext applicationContext;
//你要注入的service或者dao

UserService userService;
public static void setApplicationContext(ApplicationContext applicationContext) {
WebSocketServer.applicationContext = applicationContext;
}
3、通过userService = applicationContext.getBean(UserServiceImpl.class);方法,拿到service。(注意,后面的是getBean里面需要是服务的实现)

猜你喜欢

转载自blog.csdn.net/qq_44688861/article/details/106682939