2016-08-17 49 views
0

我有一個連接到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); 
    } 
} 
+0

您對此服務使用哪些註釋? Spring看起來並不像這些bean是基於你在那裏發現的。 – Makoto

+0

不使用任何註釋。 Bean正在使用:'ApplicationContext context = new ClassPathXmlApplicationContext(「Beans.xml」)'; – Ahmad

回答

0

爲了讓春天到人年齡爲DatabaseMapper2Impl bean的實例化和注入時,您必須創建ApplicationContext,並在該上下文中聲明bean,完全如您所做。

如果問題只是如何避免使用XML爲聲明,你可以註釋DatabaseMapper2Impl@Component,而使用

ApplicationContext context = new AnnotationConfigApplicationContext(DatabaseMapper2Impl.class); 

創建上下文。

如果你真的需要有DatabaseMapper2Impl@AutowiredDataDelegateImpl一個實例,則該實例也將不得不由Spring來控制,所以你必須建立在較高水平的背景下,使DataDelegateImpl豆以及。

相關問題