目录
@Scope 声明示例范围
1、默认情况下 Spring 容器中的实例是单例的,即无论何时何地何人访问同一个地址,它们使用的都是同一个实例对象,可以使用 @scope 注解指定实例的范围。
@Scope可选值 | 描述 |
---|---|
singleton | 在 spring 容器中的是单例,从容器中获取该 bean 时总是返回唯一的实例。不写时默认为 singleton |
prototype | 每次获取 bean 时,都会生成一个新的对象,相当于 new 操作 |
request | 在一次 http 请求内有效(只适用于 web 应用) |
session | 在一个用户会话内有效(只适用于 web 应用) |
globalSession | 在全局会话内有效(只适用于 web 应用) |
2、@Scope 可以和 @Controller、@Service、@Repository、@Component 等注解一起使用,指定实例交由 Spring 容器管理时,实例的使用范围。
3、@Scope 相当于以前配置文件中的:
<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
4、下面提供一个控制层实例进行测试:
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping("sys")
/**
* @Scope 指定实例范围:singleton、prototype、request、session、globalSession
* 同理也可以用于其它的 @Controller、@Service、@Repository、@Component 等
*/
@Scope(value = "singleton")
public class SystemController {
private int id = 1;
private static long count = 1;
/**
* http://localhost:8080/sys/get
* @return
*/
@GetMapping("get")
public String getTest() {
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode objectNode = nodeFactory.objectNode();
objectNode.put("dateTime", new Date().toString());
objectNode.put("id", id++);
objectNode.put("count", count++);
System.out.println(objectNode.toString());
return objectNode.toString();
}
}
单例时:应用启动到销毁,所有用户从始至终用的都是同一个 SystemController 实例,所以它的 id 与 count 属性完全是共享的,大家共用
多例时:应用启动后,用户每次发起请求,获取都是一个全新的 SystemController(相当于 new 了一个对象)。因为静态成员变量 count 是类变量,所以从应用启动到销毁,所有用户共享同一个, 而 id 属性每次请求都会是 1,因为每次都是新建的实例。
其它 Scope 属性也是同理,不再一一测试。
@PostConstruct 与 @PreDestroy
1、@PostConstruct 类似于 Serclet 的 inti() 方法,当 Bean 初始化时执行标记的方法。
2、@PreDestroy 类似于 Servlet 的 destroy() 方法,当 Bean 销毁时执行标记的方法。
3、下面以一个示例进行演示,提供一个 Spring 组件,交由 Spring 容器管理:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import static java.lang.System.getProperty;
/**
* 用一个组件来模拟记录一个网站被访问的总次数
* 1)用户每访问一次,总次数就加1
* 2)总次数可以存储在数据库,这里直接以文件的形式存储在磁盘上
* 3)显然如果每次访问都读写磁盘,并不明智,这里刚好利用初始化与销毁这两个时机做缓存处理
*/
@Component
public class DataCacheComponent {
//网站访问次数。使用原子类,高并发性能更好。
private static AtomicLong numberOfVisits = new AtomicLong(0);
//数据物理文件名称
private static final String fileName = "f838e6f4-b35e-49b6-a38e-106fec99f387.json";
/**
* 应用启动,DataCacheComponent bean 初始化时执行以下操作:
* 1、读取指定路径下的数据文件,不存在时创建
* 2、如果数据文件已经存在,则继续读取其中的内容,并将值赋值给成员静态变量 numberOfVisits
* 3、后续直接操作内存中的 numberOfVisits,提供性能,避免频繁操作磁盘
*
* @throws IOException
*/
@PostConstruct
public void init() throws IOException {
String java_home = getProperty("java.home");
File temp_dir = new File(new File(java_home).getParent(), "temp");
if (!temp_dir.exists()) {
temp_dir.mkdirs();
}
File temp_file = new File(temp_dir, fileName);
if (!temp_file.exists()) {
temp_file.createNewFile();
} else {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(temp_file);
if (jsonNode != null) {
numberOfVisits.set(jsonNode.get("numberOfVisits").asLong());
}
}
System.out.println("数据初始化完成:" + temp_file.getAbsolutePath() + ",numberOfVisits= " + this.numberOfVisits);
}
/**
* 应用关闭,DataCacheComponent bean 销毁时执行以下操作:
* 1、将内存中的 numberOfVisits 值持久化到磁盘文件
*
* @throws IOException
*/
@PreDestroy
public void destroy() throws IOException {
JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
ObjectNode objectNode = jsonNodeFactory.objectNode();
objectNode.put("numberOfVisits", numberOfVisits.get());
String java_home = getProperty("java.home");
File temp_dir = new File(new File(java_home).getParent(), "temp");
File temp_file = new File(temp_dir, fileName);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(temp_file, objectNode);
System.out.println("实例销毁,应用关闭,网站当前访问总次数:" + numberOfVisits.get());
}
//访问次数加1,用于其他地方调用
public long numberOfVisitsAdd() {
long l = DataCacheComponent.numberOfVisits.addAndGet(1L);
System.out.println("网站当前访问总次数:" + l);
return l;
}
}
4、提供一个控制层方法进程访问测试:
import com.wmx.web_app.component.DataCacheComponent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class VisitsController {
@Resource
private DataCacheComponent dataCacheComponent;
//http://localhost:8080/visitsTest
@GetMapping("visitsTest")
public String visitsTest() {
return String.valueOf(dataCacheComponent.numberOfVisitsAdd());
}
}