gpt4 book ai didi

java - 在 Spring Beans 中初始化字段的正确方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:39 26 4
gpt4 key购买 nike

我想知道应该如何在 Spring Beans 中初始化字段?以下是几种可能的解决方案:

<强>1。直接在声明中初始化字段

import org.springframework.stereotype.Component;

@Component
public class DeclarationInit {

private final int field = Integer.MAX_VALUE;

public int getField() {
return field;
}
}

<强>2。使用@Value注解

初始化字段
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ValueInit {

@Value("#{T(Integer).MAX_VALUE}")
private int field;

public int getField() {
return field;
}
}

<强>3。使用@Autowired注解

初始化字段
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AutowiredInit {

private int field;

@Autowired
private void initField() {
field = Integer.MAX_VALUE;
}

public int getField() {
return field;
}
}

<强>4。使用@PostConstruct注解

初始化字段
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class PostConstructInit {

private int field;

@PostConstruct
private void initField() {
field = Integer.MAX_VALUE;
}

public int getField() {
return field;
}
}

所有测试都成功并且没有显示任何差异:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SomeTestContextConfiguration.class)
public class FieldInitTest {

@Autowired
private DeclarationInit declarationInit;

@Autowired
private ValueInit valueInit;

@Autowired
private AutowiredInit autowiredInit;

@Autowired
private PostConstructInit postConstructInit;

@Test
public void shouldInitializeFieldOnDeclaration() {
assertThat(declarationInit.getField(), equalTo(Integer.MAX_VALUE));
}

@Test
public void shouldInitializeFieldWithValueAnnotation() {
assertThat(valueInit.getField(), equalTo(Integer.MAX_VALUE));
}

@Test
public void shouldInitializeFieldWithAutowiredSetter() {
assertThat(autowiredInit.getField(), equalTo(Integer.MAX_VALUE));
}

@Test
public void shouldInitializeFieldWithPostConstruct() {
assertThat(postConstructInit.getField(), equalTo(Integer.MAX_VALUE));
}
}

这些声明是否彼此相等,或者我应该只使用其中一个还是都不使用?

最佳答案

假设该值是一个常量,第一个选项最容易理解并且可以在没有 Spring 的情况下工作,从而简化单元测试。

第二个和第四个选项更复杂,并且引入了对 Spring 容器的不必要依赖,没有任何好处。第三个选项非常奇怪,因为您使用的是 @Autowired 并且没有执行依赖注入(inject)。

关于java - 在 Spring Beans 中初始化字段的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com