spring 中scope的值有四个:分别是:singleton、prototype、session、request。其中session和request是在web应用中的。
下面证明当scope为prototype时每次创建的对象是不同的。
示例代码如下:
package com.advancedWiring.ambiguityIniAutowiring2; import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; /**
* Created by ${秦林森} on 2017/6/9.
*/
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Student implements BeanNameAware{
private String name;
private Integer age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public void setBeanName(String name) {
System.out.println("the Student bean name is :"+name);
}
}
package com.advancedWiring.ambiguityIniAutowiring2; import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; /**
* Created by ${秦林森} on 2017/6/9.
*/
@Configuration
@ComponentScan
public class StudentConfig { }
package com.advancedWiring.ambiguityIniAutowiring2; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* Created by ${秦林森} on 2017/6/9.
*/
public class Test {
public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(StudentConfig.class);
Student student = ac.getBean(Student.class);
Student student2 = ac.getBean(Student.class);
System.out.println(student==student2);
}
}/**output:
false/
上面的测试类的运行结果是false,就说明了在scope为prototype时,spring每次创建的bean都是一个全新的对象。