使用spring的时候,我们一般都是使用@Component实现bean的注入,这个时候我们的bean如果不指定@Scope,默认是单例模式,另外还有很多模式可用,用的最多的就是多例模式了,顾名思义就是每次使用都会创建一个新的对象,比较适用于写一些job,比如在多线程环境下可以使用全局变量之类的
创建一个测试任务,这里在网上看到大部分都是直接@Scope(“prototype”),这里测试是不生效的,再加上proxyMode才行,代码如下:
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Test {
public static int count=0;
private Date birthday;
public Test(){
this.birthday=new Date();
count++;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
@Controller
public class IndexController {
@Autowired
Test test;
@GetMapping("/test")
@ResponseBody
private String test() {
return test.getBirthday().toString()+Test.count;
}
}