我有一个连接到MySQL数据库的小型Java应用程序。对于数据库连接只有,我想用Spring来管理基于JNDI的连接池。如何使用@Autowired而不是手动加载Spring bean?
我有一个工作实现上述,但这需要手动加载JNDI连接bean,而我想使用@Autowired。
如何将我的工作代码转换为使用@Autowired
获取JNDI连接的工作代码?
这是我的beans.xml文件(里面的src/main/resources文件夹):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns= ....>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/Database"/>
</bean>
<bean id="databaseMapper2Impl"
class="com.dataaccess.DatabaseMapper2Impl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
的是我DatabaseMapper2Impl
类的部分:
public class DatabaseMapper2Impl {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public OrderDTO getOrder(String orderNumber, String envToUse) {
String getOrderSql = "SELECT * FROM REPORTING.ORDER where ORDER_NUMBER = ? limit 1";
List<OrderDTO> orders = jdbcTemplateObject.query(getOrderSql, new Object[] { orderNumber }, new OrderMapper());
if (orders == null || orders.isEmpty()) {
return null;
} else {
return orders.get(0);
}
}
}
这是类哪里JNDI连接bean被手动实例化:
public class DataDelegateImpl {
public OrderDTO getOrder(String orderNumber, String envToUse) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
DatabaseMapper2Impl x = (DatabaseMapper2Impl) context.getBean("databaseMapper2Impl");
return x.getOrder(orderNumber, envToUse);
}
}
您对此服务使用哪些注释? Spring看起来并不像这些bean是基于你在那里发现的。 – Makoto
不使用任何注释。 Bean正在使用:'ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”)'; – Ahmad