spring中的特殊的bean
核心代码如下:
class DButil
{
private String drivername;
private String name;
private String url;
private String pwd;
//生成set,get方法....
}
beans.xml
<bean id="dbutil" class="com.dispatch.DBUtil">
<property name="name" value="${db1.name}" />
<property name="pwd" value="${db1.pwd}" />
<property name="drivername" value="${db1.drivername}" />
<property name="url" value="${db1.url}" />
</bean>
<bean id="dbuti2" class="com.dispatch.DBUtil">
<property name="name" value="${db2.name}" />
<property name="pwd" value="${db2.pwd}" />
<property name="drivername" value="${db2.drivername}" />
<property name="url" value="${db2.url}" />
</bean>
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>com/dispatch/db1.properties</value>
<value>com/dispatch/db2.properties</value>
</list>
</property>
</bean>
也可以通过<context:property-placeholder location="com/dispatch/db1.properties,com/dispatch/db2.properties"/>
db1.properties
db1.name=sa
db1.pwd=789123
db1.drivername=com.microsoft.sqlserver.jdbc.SQLServerDriver
db1.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=Ryc1;
db2.properties
db2.name=sa3
db2.pwd=78912311
db2.drivername=com.microsoft.sqlserver.jdbc.SQLServerDriver3
db2.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=Ryc14;
ApplicationContext ac = new ClassPathXmlApplicationContext("com/dispatch/beans.xml");
DBUtil dbUtil1 = (DBUtil) ac.getBean("dbutil");
System.out.println(dbUtil1.getDrivername()+"\n" + dbUtil1.getUrl());
DBUtil dbUtil2 = (DBUtil) ac.getBean("dbuti2");
System.out.println(dbUtil2.getDrivername()+"\n" + dbUtil2.getUrl());
得到结果如下:
com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc:sqlserver://127.0.0.1:1433;databaseName=Ryc1;
com.microsoft.sqlserver.jdbc.SQLServerDriver3
jdbc:sqlserver://127.0.0.1:1433;databaseName=Ryc14;