如何使用构造函数@Autowire bean [英] How to @Autowire bean with constructor

查看:695
本文介绍了如何使用构造函数@Autowire bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to define a bean and @Autowire org.springframework.jdbc.object.StoredProcedure which required 2 constructor. Is there a way I can pass constructor argument while wiring these beans ? Below is my code:

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

    @Autowired
    private StoredProcedure procedure;

......
}

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

Here StoredProcedure have a constructor to pass jdbctemplate and procedure name, which is dynamic.

推荐答案

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

Maybe I do not understand the question, but you don't need constructor params while wiring, you configire your bean (StoredProcedure) in context.xml

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

Spring使用给定的构造函数args创建它并将bean注入到字段中

Spring creates it with the given constructor args and injects the bean into your field

@Autowired
private StoredProcedure procedure;

如果不想使用xml,它不会改变想法

If dont want to use xml it does not change the idea

@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");
    }
...

这篇关于如何使用构造函数@Autowire bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆