gpt4 book ai didi

java - 如何使用构造函数@Autowire bean

转载 作者:行者123 更新时间:2023-11-29 03:38:31 27 4
gpt4 key购买 nike

我正在尝试定义一个需要 2 个构造函数的 bean 和 @Autowire org.springframework.jdbc.object.StoredProcedure。有没有一种方法可以在连接这些 bean 时传递构造函数参数?下面是我的代码:

@Component("procedure")
public class ExecuteStoreProcedure extends AbstractImutableDAO{

@Autowired
private StoredProcedure procedure;

......
}

这里StoredProcedure有一个构造函数来传递jdbctemplate和过程名称,这是动态的。

最佳答案

也许我不明白这个问题,但是你在连接时不需要构造函数参数,你在 context.xml 中配置你的 bean (StoredProcedure)

<bean id="proc1" class="org.springframework.jdbc.object.StoredProcedure">
<constructor-arg name="ds" ref="ds" />
<constructor-arg name="name" value="proc1" />
</bean>

Spring 使用给定的构造函数参数创建它并将 bean 注入(inject)到您的字段中

@Autowired
private StoredProcedure procedure;

如果不想使用 xml 也不会改变想法

@Configuration
@PropertySource("spring.properties")
@EnableTransactionManagement
public class Test3 {
@Autowired
Environment env;

@Bean
public ExecuteStoreProcedure getExecuteStoreProcedure() {
...
}

@Bean
public DataSource getDataSource() {
...
}

@Bean
public StoredProcedure getStoredProcedure() {
return new MyStoredProcedure(getDataSource(), "proc1");
}
...

关于java - 如何使用构造函数@Autowire bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14234676/

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