微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我应该在春季单例豆中完全使用静态

如何解决我应该在春季单例豆中完全使用静态

正如我刚才所读,是我创建的春豆为单例。我目前在为Logger,重用变量和一些我想只存在一次的列表使用static关键字。

但是因为alls bean是单例的,所以我正在考虑只是从所有对象中删除静态对象。

  const [searchPerfume,setSearchPerfume] = useState("");
  // Filter the data based on the search string
  const filteredPerfumes = useMemo(() => {
    return data.filter((perfume) =>
      perfume.name.toLowerCase().includes(searchPerfume.toLowerCase())
    );
  },[data,searchPerfume]);

  // Paginate the data
  const [currentPage,setCurrentPage] = useState(1);
  const [perfumesPerPage,setPerfumesPerPage] = useState(3);
  const currentPerfumes = filteredPerfumes.slice(
    (currentPage-1) * perfumesPerPage,currentPage * perfumesPerPage
  );
  const pages = Math.ceil(filteredPerfumes.length / perfumesPerPage);
  // Reset current page if there are fewer pages than the current page
  useEffect(() => {
    if (currentPage > pages) {
      setCurrentPage(1);
    }
  },[currentPage,pages]);
  // Get the range of pages in an array
  const pageNumbers = Array(pages)
    .fill(null)
    .map((val,index) => index + 1);

private static final Logger LOGGER = LoggerFactory.getLogger(MatchmakingService.class);
private static final List<Lobby> QUEUE_BLOCKED = new ArrayList<>();

我的问题是,我应该在春季环境中完全使用“静态”吗?如果是,为什么?

解决方法

Spring的设计使您在大多数情况下都可以避免使用静态字段。

拥有一个最终的静态记录器是完全可以的。记录器是线程安全的,旨在用于这种方式。

具有静态最终常量是可以的。

除记录器外,应避免任何不可改变的静态变量。

也不要将实例变量用于会话状态(与服务调用者执行的操作相关的状态),因为其他调用者可以访问和更改该状态。

如果您要使用实例变量或静态变量进行缓存,请摆脱它们,并配置一个缓存管理器。

如果您的代码将配置数据存储在静态字段中,请使其成为实例字段,并使用spring读取配置数据。

,

在类中使用静态记录器通常是有意义的,如果它正在记录相同的文件或输出流(例如System.out),则无论哪个实例记录了什么。代码段中的队列是否应该是静态的取决于其使用方式,因此如果没有更多详细信息就无法回答。

,

好问题。我认为,如果您的业务场景始终处于相同的春季环境中,则不应使用静态。原因是弹簧bean在一个弹簧上下文中是单个。但是bean在不同的弹簧上下文中具有不同的实例。下面是示例代码:

//  The first Spring Bean Context
ApplicationContext context1 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml");
Biz b1 = context1.getBean("myBean",Biz.class);

//  The second Spring Bean Context
ApplicationContext context2 = new FileSystemXmlApplicationContext("classpath:/ApplicationContext.xml");
Biz b2 = context2.getBean("myBean",Biz.class);

//  The result is false,because of creating two instances of Biz
System.out.println(b1 == b2);

但是静态变量在一个JVM中只有一个实例。因此,为了提高性能和增强鲁棒性,应该更频繁地使用static。换句话说,您不能在程序中将所有类都当作bean。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。