[英]How to use @Autowired instead of manually loading Spring beans?
我有一個連接到MySQL數據庫的小型Java應用程序。 僅用於數據庫連接,我想使用Spring來管理基於JNDI的連接池。
我有一個適用的上述實現,但是這需要手動加載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管理DatabaseMapper2Impl
Bean的實例化和注入,您將必須創建ApplicationContext
,並在該上下文中聲明該Bean,就像您所做的一樣。
如果問題僅在於如何避免使用XML進行聲明,則可以使用@Component
注釋DatabaseMapper2Impl
,而應使用
ApplicationContext context = new AnnotationConfigApplicationContext(DatabaseMapper2Impl.class);
創建上下文。
如果確實需要將DatabaseMapper2Impl
@Autowired
到DataDelegateImpl
的實例中,則該實例也必須由Spring控制,因此您必須在更高級別上創建上下文,並使DataDelegateImpl
成為bean。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.