利用Spring2.0的AOP功能向Domain Model注入DAO

阅读更多
目前在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:xsi=" http://www.w3.org/2001/XMLSchema-instance"
 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"> 
 
    class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  
     value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
  
  
  
  
  
  
 
   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  
   
  

  
   
    com.zhenuu.model.User
   

  

  
  
   
    
     org.hibernate.dialect.MySQLInnoDBDialect
    

    true
   

  

 
 
 
  
 
 
 
  
 
 
 
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

你可能感兴趣的:(AOP,DAO,Spring,Bean,Hibernate)