如果我尝试注入(inject)具有 Web 感知范围(即 session 范围、请求范围)的 bean,则注入(inject)器会忽略该 bean。不调用 bean 方法和对象构造函数。这只发生在我声明的类中,因为我可以为标准库类型(例如 List 或 Map)注入(inject) session 范围的 bean。此外,如果我使用单例或原型(prototype)作用域,注入(inject)工作得很好。
有人可以解释一下这种奇怪的行为吗?我创建了一个准系统示例来演示该问题。 (我也尝试过搜索,但找不到遇到此问题的人。)
我想要注入(inject)的类
public class CustomObj{
public String field;
public CustomObj(){
System.out.println("CustomObj constructor called");
}
}
配置文件
@Configuration
public class Config {
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public List<String> userValues() {
List<String> list = new ArrayList<String>();
list.add("This gets initialized");
return list;
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public CustomObj customObj() {
CustomObj obj = new CustomObj();
obj.field = "This doesn't";
return obj;
}
}
注入(inject)对象的 Controller
@RestController
@RequestMapping("/test")
public class TestController{
@Autowired
List<String> userValues;
@Autowired
CustomObj customObj;
@RequestMapping("/pleasework")
public String please(){
return "List values: "+Arrays.toString(this.userValues.toArray())
+ " Obj value: "+this.customObj.field;
}
}
主要
@SpringBootApplication
public class SessionbeansApplication {
public static void main(String[] args) {
SpringApplication.run(SessionbeansApplication.class, args);
}
}
访问/test/pleasework 会输出List values: [This getsinitialed] Obj value: null
,表明 List 已正确注入(inject),但 CustomObj 未正确注入(inject)。
最佳答案
如果运行代码,输出将类似于List value: [This getsinitialed] Obj value: null
您没有收到 NullpoiterException
,这意味着您的 CustomObj-bean
已创建
您应该在 CustomObj 中使用 getter 和 setter。
并使用 getter 访问字段: this.customObj.getField();
@RequestMapping("/pleasework")
public String please(){
System.out.println(userValues + " and " + customObj);
return "List values: "+ Arrays.toString(this.userValues.toArray())
+ " Obj value: " + this.customObj.getField();// <--- use getter
}
在 CustomObj
中添加 toString()
也可以工作
class CustomObj {
public String field;
public CustomObj(){
System.out.println("CustomObj constructor called");
}
@Override
public String toString() {
return "CustomObj{" +
"field='" + field + '\'' +
'}';
}
}
....
@RequestMapping("/pleasework")
public String please(){
System.out.println(userValues + " and " + customObj);
return "List values: "+ Arrays.toString(this.userValues.toArray())
+ " Obj value: " + this.customObj; //<---- use toString()
}
关于java - Spring Boot 未注入(inject)具有 Web 感知范围的 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58999084/