java - 将java变量转换为spring bean
问题描述
我正在开发 Spring Boot 应用程序。我想在类文件中将一个变量定义为 bean,以便它只被初始化一次。下面是源代码。
Configuration cfg = new Configuration();
//Load template from source folder
Template template = cfg.getTemplate("src/helloworld.ftl");
// Build the data-model
Map<String, Object> data = new HashMap<String, Object>();
data.put("message", "Hello World!");
// Console output
Writer out = new OutputStreamWriter(System.out);
template.process(data, out);
out.flush();
我想在应用程序启动期间仅初始化一次配置对象 cfg 和模板(从 2 行代码开始),然后在应用程序类中需要时使用它们。我怎样才能用bean实现这一点?或者有没有其他更好的方法来实现这一点?
解决方案
创建一个新类并使用@Configuration 注解在应用程序启动时加载bean。
@Configuration
public class SpringConfiguration{
@Bean
public Configuration getConfigurationBean(){
return new Configuration();
}
}
推荐阅读
- spring - 使用方法级别安全性在 Spring Security 中授权请求
- azure-active-directory - 如何使用来自另一个应用服务的 MSI 调用 AAD 保护的应用服务 Web API
- development-environment - OpenAI-Gym 中的自定义环境
- ios - 从大标题页过渡到小标题页时出现导航间隙
- r - tidyR 嵌套和完整:避免 group_by (或数据表等价物)
- node.js - 如何将我的节点项目与 Angular 合并?
- python - 如果变量只包含数字,如何知道变量是分类变量还是数值变量?
- android - 底部工作表不出现,留在 Android 中的 ArFragment 后面
- angular - 具有纯打字稿类实例化的同步角度代码
- ios - 使用 swift 更改 uitableView 特定单元格的标签文本