如何自动获取Springbean对java字段的引用
下面是我的SpringXML如何自动获取Springbean对java字段的引用,spring,jdbctemplate,Spring,Jdbctemplate,下面是我的SpringXML <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
因此,我只想使用jTemplate
,而不只是执行JdbcTemplate-jTemplate=(JdbcTemplate)context.getBean(“jTemplate”)
对不起,伙计们,我对Spring有点陌生,如果你们不明白我说的话,请再问我。使用自动布线,它有三种方式
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" autowire="byName">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean name="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
您使用过struts、wicket等web框架吗?@Kalhar,谢谢,但它不起作用,
jTemplate
对象为空。下面显示的我的类,公共类SpringTest{@Autowired JdbcTemplate jTemplate;公共字符串testMethod()抛出SQLException{jTemplate.update(“如果存在,则删除表;”;}
您需要声明一个bean,或者只声明元素也包括
和基本包
包括您的class@Kalher请向我解释更多,我如何将其添加到我现有的bean定义中并使用它..Niranjan,是的,我添加了组件扫描,但是我认为它可以在不使用XMLBean定义的情况下将类定义为bean。为此,还需要在类的顶部添加@Component。
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" autowire="byName">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean name="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
@Autowired
private JdbcTemplate jTemplate;