从单例更改为原型,@Scope( "prototype" )



我希望/dog2 是不同的对象,但我仍然不知道为什么 @Scope("prorotype"( 对我不起作用。我尝试使用另一个范围,但仍然存在相同的问题 - 我转到/dog 然后转到/dog2,我在两个"Sharo"上看到,而不是在/dog2 上看到"null">

春季项目申请.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();
    }
}

动物控制器.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();
}
}

狗控制器.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;
}
}

您同时使用 @Bean@Component 注释进行Dog,而您应该选择一个或另一个。删除@Bean并向类中添加@Scope Dog,或者从类中删除@Component批注。

看起来您有语法错误。尝试

@Scope("prototype")

如果这不能解决您的问题,请分享您的动物和狗类。

SpringMVC 中的控制器是单例。在多个请求之间,您的类变量将共享。您可以尝试在控制器类上方添加@Scope("请求"(注释。

最新更新