我希望/dog2 成为不同的对象,但我仍然不知道为什么 @Scope("prorotype") 不适合我。我尝试使用另一个范围,但仍然存在相同的问题 - 我转到/dog,然后转到/dog2,我在两个“Sharo”上看到,而不是在/dog2 上看到“null”
SpringProjectApplication.java
package com.example.demo.springproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import com.example.demo.springproject.entities.Animal;
import com.example.demo.springproject.entities.Dog;
@SpringBootApplication
public class SpringprojectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringprojectApplication.class, args);
}
@Scope("prototype")
@Bean
public Animal getDog() {
return new Dog();
}
}
AnimalController.java
package com.example.demo.springproject.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.springproject.entities.Animal;
@Controller
public class AnimalController {
@Autowired
private Animal dog;
@GetMapping("/dog2")
@ResponseBody
public String getDog() {
if (dog.getName() == null) {
return "null";
}
return dog.getName();
}
}
DogController.java
package com.example.demo.springproject.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.springproject.entities.Animal;
@Controller
public class DogController {
@Autowired
private Animal dog;
@GetMapping("/dog")
@ResponseBody
public String getHomePage() {
dog.setName("Sharo");
return dog.getName();
}
}
编辑: 狗.java
package com.example.demo.springproject.entities;
import org.springframework.stereotype.Component;
@Component
public class Dog implements Animal {
private String name;
public Dog() {
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
最佳答案
当您应该选择其中之一时,您同时对 Dog
使用了 @Bean
和 @Component
注释。删除 @Bean
并将 @Scope
添加到 Dog
类,或者从该类中删除 @Component
注释.
关于java - 使用 @Scope ("prototype"从单例更改为原型(prototype)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451188/