首页 > 解决方案 > Spring 创建两个 @Configuration bean 启动

问题描述

我有以下课程:

@Configuration
public class EndpointStatus {

private static final Logger serverLogger = LogManager.getLogger(EndpointStatus.class);

private Long id;
private volatile Status status;

@OneToOne
private volatile CurrentJob currentJob;

public enum Status {
    AVAILABLE,
    BUSY
}

@Bean
@Primary
public EndpointStatus getEndpointStatus() {
    serverLogger.info("STATUS CREATED");
    return new EndpointStatus();
}

public EndpointStatus() {
}

public CurrentJob getCurrentJob() {
    return currentJob;
}

public void setCurrentJob(CurrentJob currentJob) {
    this.currentJob = currentJob;
}

public Status getStatus() {
    return status;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public void setStatus(Status status) {
    this.status = status;
}

public boolean isBusy() {
    return getStatus() == Status.BUSY;
}

Bean 用于使用 @Component 注释的端点

然后我尝试在端点中获取bean,例如

ApplicationContext ctx = new AnnotationConfigApplicationContext(EndpointStatus.class);
EndpointStatus sc = ctx.getBean(EndpointStatus.class);

EndpointStatus不在其他任何地方使用。

据我所知,应该没有理由创建第二个 bean...

但是在启动时我总是得到

INFO 6169 [main] c.e.k.d.r.m.i.EndpointStatus             : STATUS CREATED
INFO 6169 [main] c.e.k.d.r.m.i.EndpointStatus             : STATUS CREATED

我在这里做错了什么?

编辑:

尝试了所有给出的答案都无济于事..

我的课现在看起来像这样

@Configuration
public class EndpointStatusConfig {

private static final Logger serverLogger = LogManager.getLogger(JavaXRest.class);

private Long id;
private volatile Status status = EndpointStatusConfig.Status.AVAILABLE;

@OneToOne
private volatile CurrentJob currentJob;

public enum Status {
    AVAILABLE,
    BUSY
}

@Bean
@Primary
public EndpointStatusConfig getEndpointStatus() {
    serverLogger.info("STATUS CREATED");
    return new EndpointStatusConfig();
}

public CurrentJob getCurrentJob() {
    return currentJob;
}

public void setCurrentJob(CurrentJob currentJob) {
    this.currentJob = currentJob;
}

public Status getStatus() {
    return status;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public void setStatus(Status status) {
    this.status = status;
}

public boolean isBusy() {
    return getStatus() == Status.BUSY;
}

  } 

无论@Component 还是@Configuration,在端点调用sc 都会导致创建的数百个bean 使应用程序崩溃...

EDIT2:这只会越来越糟......现在甚至打电话给

if ( sc.isBusy() ) { return Response.ok( sc.getCurrentJob() ).type(MediaType.APPLICATION_JSON).build(); }

将跳转到@Bean 并在应用程序崩溃之前创建尽可能多的 EndpointStatus 对象......@Component 在启动时创建一个,然后创建数千个。@Configuration 将在启动时创建 2 个,然后还会创建数千个......

标签: javaspringconfiguration

解决方案


只需将您的配置类的名称从 EndpointStatus 更改为 EndpointStatusConfig,这将只创建一个具有 EndpointStatus 类的 bean。

当您将 EndpointStatus 注释为 @Configuration 和 @Bean 时,它会创建 2 个 Bean。


推荐阅读