将java变量转换为spring bean

问题描述 投票:0回答:2

我正在从事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和模板(从代码的两行开始),然后在应用程序类中需要的地方使用它们。如何用bean实现这一目标?还是有其他更好的方法来实现这一目标?

java spring-boot javabeans
2个回答
0
投票

您可以做的一件事就是将变量的实例化和初始化放在自己的方法中,并用@Bean注释对每个方法进行注释。

如果执行此操作,则应使用@Configuration注释该类。

您的2种方法看起来像这样:

@Configuration
public class ConfigurationBean {
    @Bean
    public Configuration configuration() {
        return new Configuration();
    }

    @Bean
    public Template template() {
        return configuration().getTemplate("...");
    }
}

此外,如果您不想将Configuration实例化为单独的bean,则可以合并上面的2种方法。

=======更新以评论中的问题========>

[例如,如果要在其他类中使用新定义的Template bean,则需要用@Component注释这些类,以便它们也成为bean。

示例:

@Component
public class OtherClassBean {
    private final Template template;

    public OtherClassBean(Template template) {
        this.template = template;
    }
}

请注意,因为从现在开始,您不能手动实例化OtherClassBean,这意味着在99%的情况下,类似new OtherClassBean(...)的行都是错误的,并且可能导致意外的行为。

这是因为所有bean都应由Spring管理,只有在Spring实例化这些类时才能实现。

此经验法则的唯一例外是我的最初答案,在该示例中,您以用@Bean注释的方法实例化了bean。

我知道对于大多数尝试学习此方法的人来说,这是一个令人困惑的主题,因此不要害羞地问更多问题。


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.