@Scope("singleton")一个简短的例子(默认)和之间有什么区别@Scope("prototype"):
DAO类:
package com.example.demo;
public class Manager {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
配置:
@Configuration
public class AppConfiguration {
@Bean
@Scope("singleton")
public Manager getManager(){
return new Manager();
}
}
和主应用程序:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.example.demo");
context.refresh();
Manager firstManager = context.getBean(Manager.class);
firstManager.setName("Karol");
Manager secondManager = context.getBean(Manager.class);
System.out.println(secondManager.getName());
}
}
在此示例中,结果是:Karol即使我们仅为firstManager对象设置此名称。这是因为 Spring IoC 容器创建了一个对象实例。但是,当我们将范围更改为@Scope("prototype")Configuration 类时,结果是:null因为 Spring IoC 容器在发出对该 bean 的请求时会创建该对象的新 bean 实例。