我正在使用 Eclipse Juno IDE 和 phpMyAdmin。
我有java应用程序,为此应用程序我在phpMyAdmin中创建了一个数据库。 现在,我有一个数据库方法的接口(interface)。 假设界面是这样的:
public interface DBInterface{
public Vector<Employees> getAllEmplyess();
public void addNewEmployee(int ID, String name,String department);
}
现在我需要通过两种方式实现这个接口(interface):
1) JPA
2) JDBC
假设我通过上述两种方式实现了该接口(interface)。
如何在 applicationContext.xml 文件中选择使用 spring 机制? 它是如何工作的?
最佳答案
为什么需要 JPA 和 JDBC 实现(JPA 基于 JDBC)?
区分两者的方法是创建 2 个独立的 DAO 类(都实现您的接口(interface))
public class JDBCDao implements DBInterface {...}
public class JPADao implements DBInterface {...}
并在需要时在 spring xml(应用程序上下文文件)中注入(inject)适当的 DAO bean。
例如,应用程序上下文 xml 将如下所示:
(EmployeeService 类的 dao
成员的类型为 DBInterface
)
<bean id="JPADAO" class="com.yourpackage.JPADao".../>
<bean id="JDBCDAO" class="com.yourpackage.JDBCDao".../>
<bean id="EmployeeService" class ....>
<property name="dao" ref="JDBCDAO" />
...
</bean>
或者您也可以在代码中注入(inject) DAO。
ApplicationContext ctx = AppContext.getApplicationContext();
EmployeeService svc = (EmployeeService) ctx.getBean("EmployeeService");
DBInterface dao = (DBInterface) ctx.getBean("JPADAO");
svc.setDao(dao);
关于java - 在使用 spring applicationContext 的接口(interface)实现之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12246550/