有没有办法在没有xml或属性文件的应用程序上下文中存储java变量/对象 [英] Is there a way to store java variable/object in application context without xml or properties file

查看:34
本文介绍了有没有办法在没有xml或属性文件的应用程序上下文中存储java变量/对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Spring Boot 应用程序的应用程序上下文中存储特定变量(字符串或对象).但我不想使用 xml 或属性文件来存储它.

I want to store a particular variable (String or Object) in application context in spring boot application. But I don't want to use an xml or properties file for storing it.

将有一个函数将数据存储在应用程序上下文中.我应该能够检索、修改、删除或添加更多数据.

There will be a function which will store the data in application context. I should be able to retrieve it, modify it, delete it or add more data.

基本上我想在初始化完成后将数据存储在应用程序上下文中.

Basically I want to store data in application context after its initialization has been done.

推荐答案

如果你创建一个类并在上面加上@Configuration注解,并用@Bean声明一些bean> 注释,它们成为应用程序管理的 bean.

If you create a class and put @Configuration annotation over it, and declare some beans with @Bean annotation, they become application managed beans.

@Configuration
public class ConfigurationClass {

    @Bean("myString")
    public String getString() {     
        return "Hello World";
    }
}

然后,您可以在代码的任何位置调用 AnnotationConfigWebApplicationContext.getBean("myString") 来获取您的 bean.

Then anywhere from your code you can call AnnotationConfigWebApplicationContext.getBean("myString") to get your bean.

现在可能存在并发问题(如 davidxxx 所述).为此,您可以使用 SimpleThreadScope.看看这个链接 了解如何将其注册到应用程序上下文以及该注释的放置位置(或谷歌).

Now there could be concurrency issues (as mentioned by davidxxx ). For that you can use SimpleThreadScope. Look at this link to learn how to register it with application context and where to place that annotation (or google it).

或者如果您不想处理那个,那么 @Scope("request") 应该会有所帮助.带有 @Scope("request") 的 bean 将为每个新传入的请求创建,因此它的线程安全性得到保证,因为它在每次新请求传入时创建.

Or if you don't want to deal with that, then a @Scope("request") should help. The bean with @Scope("request") would be created for every new incoming request thus it’s thread safety is guaranteed since it’s created every time a new request comes in.

这篇关于有没有办法在没有xml或属性文件的应用程序上下文中存储java变量/对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆