首页 > 解决方案 > 将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实现这一点?或者有没有其他更好的方法来实现这一点?

标签: javaspring-bootjavabeans

解决方案


创建一个新类并使用@Configuration 注解在应用程序启动时加载bean。

@Configuration
public class SpringConfiguration{

    @Bean
    public Configuration getConfigurationBean(){
        return new Configuration();
    }
}

推荐阅读