gpt4 book ai didi

java - 使用@Component 和@Autowired 时的Spring bean 原始属性?

转载 作者:搜寻专家 更新时间:2023-11-01 02:16:28 24 4
gpt4 key购买 nike

如何为 bean 的原始属性设置值?

既然我们有@Component注解,还有@Autowired注解也是绑定(bind)实例依赖的,那么原始属性呢?

@Component
class Person{
@Autowired
Address address;

int age /// what about this one?
}

最佳答案

对于基元,您可以使用 @Value 注释。通常的情况是有一个 PropertyPlaceholderConfigurer 从属性文件加载值,然后有 @Value("${property.key}")

您还可以将您的值定义为 beans,这是更老派的做法:

<bean id="foo" class="java.lang.Integer" factory-method="valueOf">
<constructor-arg value="20" />
</bean>

然后

@Autowired
@Qualifier("foo")
private int foo;

关于java - 使用@Component 和@Autowired 时的Spring bean 原始属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5467803/

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