对packagesToScan与context:component-scan与tx:annotation-driven的理解

[转载]对packagesToScan与context:component-scan与tx

(2012-05-19 23:34:31)
标签:

转载

 

以前编写实体类Entity的时候,都需要配置映射文件.hbm.xml,同时需要在sessionFactory中配置映射文件或映射目录
使用annotation时需要将sessionFactory定义为:
<bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
【Entity】
文件映射
<propertyname="mappingResources">
  <list>
   <value> ...hbm.xml</value>
   ....
  </list>
</property>

或者 目录映射
<propertyname="mappingDirectoryLocations">
   <list>
     <value>classpath:/../hbm/</value>
      ....          
  </list>
</property>

现在可以使用Annotation来简化配置(jdk5 spring2.5 hibernate3.3)
在sessionFactory中配置
<property name="packagesToScan"value="包名.*"/>
然后在Entity中定义类名的地方注释:@MappedSuperclass就可以自动完成载入,不用再配置.

【service】
以前编写service时要先编写Entity,Dao然后进行Dao配置进行自动注入Service
<bean id="mailDao"
 class="com.gzpost.cps.dao.hibernate.MailDaoHibernate">
  <propertyname="sessionFactory">
   <reflocal="sessionFactory" />
  </property>
 </bean>
 <bean id="mailSearchService"
 class="com.gzpost.cps.service.impl.MailSearchServiceImpl">
  <propertyname="mailDao">
   <reflocal="mailDao" />
  </property>
 </bean>
当然也可以在Spring配置中申明按名或按类自动注入,可以少配置属性,但是Bean还是要配置的

现 在可以使用SpringSide的SimpleHibernateTemplate范型Dao,直接在Service层创建,同时Service采用 @Service注释来自动注册服务,在要注入参数的地方注释:@Autowired,就可以自动注入参数,前提是必须在Spring中配置
<!-- 使用annotation自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
 <context:component-scanbase-package="包名" />
 这样就搞定了,可以减少好多的配置
【transaction】
<!-- 使用annotation定义事务 -->
<tx:annotation-driventransaction-manager="transactionManager" />
在服务类定义处注释:@Transactional,还可以在具体方法出定义@Transactional(readOnly=true)//使用readOnly可以提高性能
同一个方法里,事务可以传递,可以解决Lazy问题,可以不再使用:openSessionInView,使用此切面(aspect),必须在实现 类(和/或类里的方法)、而不是类的任何所实现的接口上面进行注解
例如:
   @Transactional
    public classUserManagerInCatche {
   @Transactional(readOnly=true)//使用readOnly可以提高性能
    public void initResourceCache() {
     if (!cacheInitialized) {
      synchronized (this) {
       List<Resource> resources =userManager.getAllResorece();
       for (Resource resource : resources) {
        resourceDetailsInCache(resource);//resourceDetailsInCache方法会使用initResourceCache方法的事务
       }
       cacheInitialized = true;
      }
     }
    }
    private voidresourceDetailsInCache(
      Resource resource) {
   //  GrantedAuthority[] authorities =role2authorities(userManager.getRolesByResourceId(resource.getId()));
     GrantedAuthority[] authorities =role2authorities(resource.getRoles());
     
     ResourceDetails rd = newgzpost.security.resourcedetails.Resource(resource
       .getResString(), resource.getResType(), authorities);
     resourceCache.putAuthorityInCache(rd);
    }
    }

posted @ 2015-02-03 17:49  carrot__lsp  阅读(294)  评论(0编辑  收藏  举报