目前在Spring 2.0里,可以向Domain Model对象里注入DAO,让POJO真正变成充血模型成为现实,这就意味著可以直接在POJO对象里进行业务逻辑和事物托管,只要我们在代码里用new操作符构造出来的对象都可以给Spring容器进行托管、具体使用如下:
@Configurable(autowire=Autowire.BY_TYPE) // 加上基于jdk1.5的注解
public class User {
private int id;
private String name;
private UserDao userDao;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
public interface UserDao {
public List<User> loadAll();
}
public class UserDaoImpl extends HibernateDaoSupport {
public List<User> loadAll() {
.......................
.......................
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<aop:spring-configured />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="avaJevoLI" />
<property name="maxWait" value="120000" />
<property name="maxIdle" value="10" />
<property name="maxActive" value="500" />
<property name="initialSize" value="50" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="annotatedClasses">
<list>
<value>com.zhenuu.model.User</value>
</list>
</property>
<!--
<property name="annotatedPackages">
<list>
<value>test.package</value>
</list>
</property>
-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.zhenuu.user.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="user" class="com.zhenuu.user.model.User">
<property name="userDao" ref="userDao" />
</bean>
</beans>
client.java
public class Client {
public static void main(String...args) {
new ClassPathXmlApplicationContext(new String[]{"classpath:spring.xml"});
User user = new User();
user.setId(10);
List<User> users = user.loadAll();
for(User user1 : users) {
System.out.println(user1.getName());
}
}
}
运行:
java -javaagent:G:\我的开发包\spring\spring-framework-2.0-rc2\lib\aspectj\aspectjweaver.jar Client