Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 是春天';是否重用了s@Autowired对象?_Spring_Dependency Injection - Fatal编程技术网

Spring 是春天';是否重用了s@Autowired对象?

Spring 是春天';是否重用了s@Autowired对象?,spring,dependency-injection,Spring,Dependency Injection,如果是,如何阻止这种情况?这取决于被注释的bean的范围。如果它属于范围singleton,那么它将在SpringApplicationContext中的任何地方使用相同的实例。如果它属于范围prototype,则将在每个位置使用一个新实例 <bean id="id" class="some.NewObject" scope="prototype"/> <bean id="id2" class="some.AnotherNewObject" scope="singleton"/

如果是,如何阻止这种情况?

这取决于被注释的
bean的
范围。如果它属于范围
singleton
,那么它将在Spring
ApplicationContext
中的任何地方使用相同的实例。如果它属于范围
prototype
,则将在每个位置使用一个新实例

<bean id="id" class="some.NewObject" scope="prototype"/>
<bean id="id2" class="some.AnotherNewObject" scope="singleton"/>
Class1
Class2
将收到对
some.AnotherNewObject
的相同实例的引用
Class3
Class4
将收到对
some.NewObject
的不同实例的引用

如果使用注释和包扫描进行配置,则可以使用
@Scope
注释指定范围:

@Component
@Scope("prototype")
class NewObject {
    ...
}

@Component
@Scope("singleton")
class AnotherNewObject {
    ...
}

很好,但是它如何改变注释中的范围呢?你是什么意思,你能给出更多的上下文吗?您不能使用
@Autowired
注释来更改bean的范围。但是您可以使用bean上的注释来更改范围。谢谢,这就是我要找的。我不明白为什么prototype/singleton//没有被Spring声明为枚举。我同意这篇文章,答案涉及控制器内页面的值,但这里我们可以使用原型的枚举,它将是编译时常量,范围注释将把枚举作为输入,而不是字符串。例如,Hibernate中的GeneratedValue就是这样做的。您不能使用枚举,因为Spring类的作用域是可扩展的。我可以定义自己的
范围
并将其注册到Spring的
ApplicationContext
,此时,它可以在Spring的
@Scope
注释中使用。
@Component
@Scope("prototype")
class NewObject {
    ...
}

@Component
@Scope("singleton")
class AnotherNewObject {
    ...
}
@Service
@Scope("prototype")
public class CustomerService 
{}