在通过 SpringApplicationContext 从 Controller 方法获取 bean 实例时遇到问题。我在 Controller 方法中需要的是类 B
的一个填充良好的实例。 B
类的定义如下:
@Component
public class ADep {
}
@Component
public class A {
@Autowired
private ADep aDep;
public void printDep() {
System.out.println("aDep is " + aDep);
}
}
@Component
public class B extends A {
public void printAMethod() {
super.printDep();
}
}
当以下 Controller 方法被调用时:
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, path = "/method1")
public MappingJacksonValue method1(HttpServletRequest request, HttpServletResponse response, B b) throws Exception {
b.printAMethod();
return null;
}
我看到以下响应:
aDep is null
如果我不是在 Controller 方法中获取 bean,而是从应用程序上下文中获取它,响应是不同的:
@Autowired
private ApplicationContext applicationContext;
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, path = "/hardware")
public MappingJacksonValue getHardware(HttpServletRequest request, HttpServletResponse response) throws Exception {
B b = applicationContext.getBean(B.class);
b.printAMethod();
return null;
}
结果:
aDep is ADep@2e468dfa
在后一种情况下,我需要的是一个 bean 实例。如何在不使用 SpringApplicationContext 的情况下在 Controller 方法中获取它?
最佳答案
您正试图将类型为 B 的 b 对象作为参数传递,因此在这种情况下您必须创建并提供 b 对象并将其传递给方法,我认为您正在为该参数提供一个空值,但是如果你希望你可以使用 @Autowired 而不是应用程序上下文,因为 B 已经是一个组件,就像这样:
@Autowired
private B b;
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, path = "/hardware")
public MappingJacksonValue getHardware(HttpServletRequest request, HttpServletResponse response) throws Exception {
b.printAMethod();
return null;
}
编辑:
要更改 bean 的范围,您可以在 B
类上方添加 @Scope(value = WebApplicationContext.SCOPE_REQUEST)
注释以针对不同的请求使用不同的 bean
关于java - 通过Controller方法和applicationContext获取bean的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688031/