使用@Scope从Singleton更改为Prototype(" prototype")

时间:2018-01-25 20:15:32

标签: java spring spring-boot

我希望/ dog2成为不同的对象,但我仍然不知道为什么@Scope(" prorotype")对我不起作用。我尝试了另一个Scopes,但仍然有同样的问题 - 我去/ dog然后去/ dog2,我在两个" Sharo"而是看" null" on / dog2

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();
}
}

编辑: Dog.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;
}

}

3 个答案:

答案 0 :(得分:2)

当您选择其中一个时,您正在@Bean使用@ComponentDog注释。删除@Bean并将@Scope添加到Dog类,或从班级中删除@Component注释。

答案 1 :(得分:0)

看起来你有语法错误。 试试

@Scope("prototype")而不是

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

答案 2 :(得分:-1)

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