spring 中把接口作为参数调用
先看下面两段代码:
package com.example.webflux.handler;
import com.example.webflux.pojo.Greeting;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new Greeting("Hello Spring")));
}
}
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
@Configuration(proxyBeanMethods = false)
@Import(TestRouter.class)
public class GreetingRouter {
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler){
return RouterFunctions.route(GET("/hello")
.and(accept(MediaType.APPLICATION_JSON)),
greetingHandler::hello
);
}
}
我一直想不明白为什么在route方法中传入一个class类型的形参,就能调用相应的方法?后来听了黑马李老师的视屏后才明白原因
GreetingHandler
类因为标注了注解Component
,所以在程序起动时会自动会向sprring容器中注入bean对象- route方法上标注
@Bean
表示把返回对象注入到spring容器中,如果当方法中有形参时,就会默认进行自动装配注入
自己写了一个用例测试下
package com.example.webflux.handler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
@Component
public class DemoHandler {
public Mono<String> hello(){
return Mono.just("你好,先生!");
}
}
创建了一个DemoHandler
类,并注入IOC容器中
package com.example.webflux.routers;
import com.example.webflux.handler.DemoHandler;
import org.springframework.context.annotation.Bean;
public class TestRouter {
@Bean
public String testPrint(DemoHandler handler) {
System.out.println(handler);
handler.hello().subscribe(s -> System.out.println(s));
return "ok";
}
}
创建一个配置类TestRouter
,在方法testPring
上声明@bean
注解,把DemoHandler
类作为形参传入,在方法中输出参数handler
,并输出调用方法的返回值。在GreetingRouter
类中使用Import注解导入TestRouter类。
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest(classes = {GreetingRouter.class, DemoHandler.class, GreetingHandler.class})
class WebfluxApplicationTests {
@Autowired
ApplicationContext context;
@Test
void contextLoads() {
Object o = context.getBean("testPrint");
System.out.println(o);
}
}
在测试类中获取注入到IOC容器中的bean,并打印对象,测试结果如下
注意:在测试类中需要在注解SpringBootTest
中把测试中需要的类引入,否则会报容器中没有所需要的类型
感谢李老师
视屏地址:https://www.toutiao.com/video/7088620870285034020/