我正在学习Spring(2和3),我在ClientDao中得到了这个方法
public Client getClient(int id) {
List<Client> clients= getSimpleJdbcTemplate().query(
CLIENT_GET,
new RowMapper<Client>() {
public Client mapRow(ResultSet rs, int rowNum) throws SQLException {
Client client = new ClientImpl(); // !! this (1)
client.setAccounts(new HashSet<Account>()); // !! this (2)
client.setId(rs.getInt(1));
client.setName(rs.getString(2));
return client;
}
},id
);
return clients.get(0);
}
以及以下Spring接线:
<bean id="account" class="client.AccountRON" scope="prototype">
<property name="currency" value = "RON" />
<property name="ammount" value="0" />
</bean>
<bean id="client" class="client.ClientImpl" scope="prototype">
<property name="name" value="--client--" />
<property name="accounts">
<set>
</set>
</property>
</bean>
事情是我不喜欢java代码(1)和(2)的注释行。 我将从(2)开始,我认为这是一个简单的方法:有没有办法可以在.xml文件中连接bean,告诉spring实例化ClientImpl中设置的'accounts'的集合实现?所以我可以摆脱(2)
现在转到(1):如果实施改变会发生什么?我是否真的需要为另一种实现编写另一个DAO?还是我必须构建一个BeanFactory?还是有另一个更美丽的解决方案?
谢谢!
答案 0 :(得分:3)
我在这里有点困惑 - 你为什么要在XML中定义一个ClientImpl
bean,而不是在Java中使用它?
你已经拥有了大部分解决方案,你只需要在每次迭代循环中从Spring中获取一个新的ClientImpl
:
private @Autowired BeanFactory beanFactory;
public Client getClient(int id) {
List<Client> clients= getSimpleJdbcTemplate().query(
CLIENT_GET,
new RowMapper<Client>() {
public Client mapRow(ResultSet rs, int rowNum) throws SQLException {
Client client = beanFactory.getBean(Client.class);
client.setId(rs.getInt(1));
client.setName(rs.getString(2));
return client;
}
},id
);
return clients.get(0);
}
使用这种方法,ClientImpl
的实际构造和初始化由Spring完成,而不是代码。