[英]How to @Autowire bean with constructor
I am trying to define a bean and @Autowire org.springframework.jdbc.object.StoredProcedure which required 2 constructor. 我正在尝试定义一个bean和@Autowire org.springframework.jdbc.object.StoredProcedure,它需要2个构造函数。 Is there a way I can pass constructor argument while wiring these beans ? 有没有办法在连接这些bean时传递构造函数参数? Below is my code: 以下是我的代码:
@Component("procedure")
public class ExecuteStoreProcedure extends AbstractImutableDAO{
@Autowired
private StoredProcedure procedure;
......
}
Here StoredProcedure have a constructor to pass jdbctemplate and procedure name, which is dynamic. 这里StoredProcedure有一个构造函数来传递jdbctemplate和过程名称,这是动态的。
Maybe I do not understand the question, but you don't need constructor params while wiring, you configire your bean (StoredProcedure) in context.xml 也许我不明白这个问题,但你在布线时不需要构造函数参数,你可以在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 creates it with the given constructor args and injects the bean into your field Spring使用给定的构造函数args创建它,并将bean注入到字段中
@Autowired
private StoredProcedure procedure;
If dont want to use xml it does not change the idea 如果不想使用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");
}
...
When you @Autowire a field, you're assuming that a bean of the required type already exists in the ApplicationContext. 当你@Autowire一个字段时,你假设ApplicationContext中已经存在一个所需类型的bean。 So what you need to do in order to get this code to work is to declare a such a bean (either in XML or, if you want to configure it programmatically, using @Bean- see the Spring documentation here ). 因此,为了使这些代码工作,您需要做的是声明一个这样的bean(或者,如果您想以编程方式配置它,使用@ Bean-请参阅此处的Spring文档 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.