gpt4 book ai didi

bean 构造函数中的 Java 值注入(inject)

转载 作者:行者123 更新时间:2023-12-02 01:05:55 24 4
gpt4 key购买 nike

我有一些很好的工作代码,例如:

//SpringConfiguration.class文件

package com.yet.spring.core;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class SpringConfiguration {

@Bean
@Scope("prototype")
public Client client(String id, String full_name) {

return new Client(id, full_name);

} //END: Client()

} //END: class SpringConfiguration

现在,我可以通过以下方式请求带有构造函数值的 bean“client”:

 public final static ApplicationContext app_context =
new AnnotationConfigApplicationContext(SpringConfiguration.class);

new_client = (Client) app_context.getBean(Client.class, "1", "John Smith");

如何通过 XML 配置文件来做到这一点? “constructor-arg”只能用于静态值或 bean 吗?

最佳答案

如果您确实需要使用 XML,那么它还支持构造函数注入(inject),并且它适用于基本类型、表达式和 bean。

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0" ref="dataSource"/> <!-- bean with id dataSource is defined in the same XML earlier -->
</bean>

如果您需要始终获取具有相同值的 Client bean,您可以执行以下操作

@Bean
@Scope("prototype")
public Client client(@Value("${clientId}") String id, @Value("${clientFullName}") String full_name) {

return new Client(id, full_name);
}

然后定义属性clientIdclientFullName就是一个属性文件。如果您需要每次使用不同的参数创建 Client 对象,那么您根本不需要 Spring 来实现这一点。你应该这样做

new_client = new Client("1", "John Smith");  

关于bean 构造函数中的 Java 值注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728919/

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