【spring】让spring的注解和xml配置文件变得优雅,最常用的注解

其实,对注解的使用,应该是:先用xml,对某个注解足够了解够,用上这个注解,省去部分xml。循序渐进,既少了xml配置文件的配置,也不失代码的可读性和对代码的理解。

MD,刚刚服务器挂了,害我又写一遍

使用spring,肯定得先导入spring上下文,假定存在变量springContext中

一、首先,完全不使用注解

缺点

1、配置文件会很大,可以分类写在不同xml中缓解一下

2、对于不是bean的类,它的成员变量就得从springContext那儿get

优点

统一,可读性好,用IoC注入属性

 

二、使用@Autowired

1、如果某个bean的成员也是bean,那这个成员的配置可以省去

2、克服了(一)中第二个缺点

3、代价较小,代码可读性还是很高

 

三、加入@Component等注解

被这些注解标记的类,相当于在xml中配置了bean

1、省去大量的配置

2、代价还是较小,代码可读性高

 

不足

1、用@Repository,如果UserDao继承了HibermateSupportDao,我没有办法在UserDao类中,给父类HibermateSupportDao的成员sessionFactory注入

只能在xml中配置

破坏了使用注解和xml中选择的统一性

四、使用@Transational

(一)不使用注解,配置AOP

使用事务管理,可以在配置文件中配置,用AOP实现事务管理。

<!-- 配置事务管理器 -->
    <bean
        id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
        <property name="sessionFactory" >
            <ref local="sessionFactory" />
        </property>
    </bean>
    <!-- 配置哪些方法需要哪些事务 -->
    <tx:advice
        id="txadvice"
        transaction-manager="transactionManager" >
        <tx:attributes>
            <tx:method
                name="create*"
                propagation="REQUIRED" />
            <tx:method
                name="delete*"
                propagation="REQUIRED" />
            <tx:method
                name="update*"
                propagation="REQUIRED" />
            <tx:method name="read*"
                read-only="true"
                propagation="NOT_SUPPORTED"/>
            <tx:method
                name="*"
                read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- pointcut切入点;advice,通知,即被织入的方法 。这儿是AOP-->
    <aop:config proxy-target-class="true">
        <aop:pointcut
            id="managerMethods"
            expression="execution (* org.ccnt.med.dao.TbTopicDao.*(..))" />
        <aop:pointcut
            id="managerMethods"
            expression="execution (* org.ccnt.med.dao.TbDisTopicDao.*(..))" />
        <aop:advisor
            advice-ref="txadvice"
            pointcut-ref="managerMethods" />
    </aop:config>

(二)使用@Transational注解

@Transantional相当于封装了对事务管理的AOP实现,就不用配置AOP部分了。

1、首先,在配置文件中加入tx:annotation-driven

<tx:annotation-driven transaction-manager="transactionManager" /><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

2、然后,再配置上

<!-- 配置事务管理器 -->
    <bean
        id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
        <property name="sessionFactory" >
            <ref local="sessionFactory" />
        </property>
    </bean>

3、在需要配置上事务的代码中

@Transactional
public TbDiseases read(int id) throws ServerException{
。。。
}

五、AOP使用@Aspect注解

实现方便,而且更利于代码理解,可以免去<aop:config>的配置,非常实用

原文地址:https://www.cnblogs.com/549294286/p/3017948.html