目前在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 loadAll();
}
public class UserDaoImpl extends HibernateDaoSupport {
public List loadAll() {
.......................
.......................
}
}
spring.xml
xmlns:tx=" http://www.springframework.org/schema/tx"
xmlns:aop=" http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
destroy-method="close">
org.hibernate.dialect.MySQLInnoDBDialect
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 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