1
我想從XML屬性文件加載SQL查詢並將它作爲java.util.Property
注入到我的DAO類中。這個SQLs.xml駐留在與應用程序上下文相同的目錄下(我使用Maven結構,所以它們都在src/main/resources下)。我的應用程序上下文文件看起來像如下:從XML屬性文件加載和注入屬性Bean與彈簧
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="EmployeeDAO" class="pkg.dao.EmployeeDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="oracle jdbc url" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<util:properties id="queryProps" location="classpath:SQLs.xml"/>
<bean id="employeeDAOProp" class="pkg.dao.EmployeeDAOImpl">
<property name="queryProps" ref="queryProps" />
</bean>
而且SQLs.xml
內容是:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="getEmployee">
select * from employee;
</entry>
</properties>
的DAO類:
public class EmployeeDAO {
private DataSource dataSource;
private Properties queryProps;
public Properties getQueryProps() {
return queryProps;
}
public void setQueryProps(Properties queryProps) {
this.queryProps = queryProps;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Employee getEmployee(int id) {
String sql = queryProps.getProperty("getEmployee");
}
}
我加載上下文主應用程序中的文件爲:
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
我可以加載EmployeeDAO
沒有問題,並在其getEmployee()
方法調用。即使是datasource
也可以毫無問題地提取所有需要的鍵/值。但queryProps
始終爲空。
你試過''而不是'util:properties'嗎? –
@LaabidiRaissi您可以詳細說明如何使用' '在我的DAO類中使用屬性嗎? –
Malvon