1. 程式人生 > >SSH開發中的註解使用

SSH開發中的註解使用

blog epo -i resource class port pooled 開啟事務 log

在SSH中使用註解可以減少配置XML文件,畢竟隨著項目規模的擴大,配置bean將把Spring的配置文件(applicationContext.xml)變得很混亂

在Spring的配置文件中開啟註解掃描

<context:component-scan base-package="cn.lynu"></context:component-scan>

註意這個base-package就是指定了要掃描的包範圍,這裏可以指定一個共有的包名以掃描所有類的註解

這裏給一個Spring配置文件:

現在只需要配置C3P0和hibernate並開啟註解掃描就可以了

<?
xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
>

<!-- 配置c3p0連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/easyui"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 配置hibernate --> <!-- 1.先配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocations" value="classpath:hibernate.cfg.xml"></property> </bean> <!-- 2.開啟事務管理器,用註解方式使用事務 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 開啟事務,記得在需要開啟事務的類上 [email protected]--> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 開啟註解掃描 --> <context:component-scan base-package="cn.lynu"></context:component-scan> </beans>

開始使用註解

1.先從Dao開始,[email protected]

技術分享

然後是很關鍵的一步,我使用了HibernateDaoSupport,需要在Dao中註入sessionFactory,而Dao中就需要調用HibernateDaoSupport中的sessionFactory

    @Resource(name="sessionFactory")
    public void setSF(SessionFactory sf){
        super.setSessionFactory(sf);
    }

setSF這個名字不是固定的,只要是以set打頭就行了

[email protected]

技術分享

[email protected]

    private AdminDao adminDao;
    @Resource(name="adminDao")
    public void setAdminDao(AdminDao adminDao) {
        this.adminDao = adminDao;
    }

[email protected],[email protected]("prototype")指明為多實例,action都是多實例的

技術分享

[email protected]

    private AdminService adminService;
    @Resource(name="adminService")
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

SSH開發中的註解使用