Java SpringBoot没有注入具有web感知作用域的Bean
如果我尝试注入一个具有web感知作用域(即会话作用域、请求作用域)的bean,注入器将忽略该bean。不调用bean方法和对象构造函数。这只发生在我声明的类上,因为我可以为标准库类型(如List或Map)注入会话范围的bean。此外,如果我使用单例或原型作用域,则注入工作正常 有人能解释这种奇怪的行为吗?我创建了一个裸体样本来演示这个问题。 (我也尝试过搜索,但找不到有此问题的人。) 我想注入的类Java SpringBoot没有注入具有web感知作用域的Bean,java,spring,spring-boot,configuration,Java,Spring,Spring Boot,Configuration,如果我尝试注入一个具有web感知作用域(即会话作用域、请求作用域)的bean,注入器将忽略该bean。不调用bean方法和对象构造函数。这只发生在我声明的类上,因为我可以为标准库类型(如List或Map)注入会话范围的bean。此外,如果我使用单例或原型作用域,则注入工作正常 有人能解释这种奇怪的行为吗?我创建了一个裸体样本来演示这个问题。 (我也尝试过搜索,但找不到有此问题的人。) 我想注入的类 public class CustomObj{ public String field;
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;
}
}
访问/test/plesework会给出输出<代码>列表值:[这被初始化]Obj值:null,表明列表被正确注入,但CustomObj没有正确注入。如果运行代码,输出将类似于<代码>列表值:[这被初始化]Obj值:null 您没有得到
NullpoiterException
,这意味着您的CustomObj bean已创建
您应该在CustomObj中使用getter和setter。
并使用getter访问字段:this.customObj.getField()代码>
我很困惑,因为这个答案有点误导。问题不是NullPointerException,而是注入器忽略了bean。但是,您的解决方案确实有效。如果我使用getter和setter,注入器会命中断点来初始化bean。你知道为什么会这样吗?你没有得到一个空指针,所以你的bean是自动连接的。只要尝试打印this.customObj
,您就会在页面上得到输出我同意我没有得到空指针,但bean肯定不是从原始代码自动连接的。在原始代码中,Config中的bean方法被完全忽略。没有命中任何打印语句或断点。然而,如果我像你建议的那样使用getter和setter,它会自动连接。我不明白为什么添加setter会允许注入我的对象如果我使用你的代码,我会在页面中得到“列表值:[这被初始化]Obj值:null”,但控制台会打印:“CustomObj构造函数调用”。。。。所以CustomObj被注射了这很奇怪,因为我没有注射过。我会接受你的回答,因为它确实导致了我的代码工作,即使它看起来对我有误导性。谢谢你的帮助!
@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);
}
}
@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
}