1. 程式人生 > >idea專案新增spring

idea專案新增spring

配置步驟

1.新增spring的依賴包

idea可以直接右擊專案 選擇add frame support,勾選spring即可

2.建立applicationContext.xml

在src的直接子目錄下建立 applicationContext.xml

這裡給出一個applicationContext.xml 的例項,以及註釋解釋

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
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"
>
<!-- 掃描有註解的檔案 base-package 包路徑 --> <context:component-scan base-package="service.imp, action, dao.imp"/> <!-- 定義 Autowired 自動注入 bean --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <!-- 宣告式容器事務管理 ,transaction-manager指定事務管理器為transactionManager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*User"/> <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true"/> </tx:attributes> </tx:advice> <!-- 定義切面,在service包及子包中所有方法中,執行有關的hibernate session的事務操作 --> <aop:config> <!-- 只對業務邏輯層實施事務 --> <aop:pointcut id="serviceOperation" expression="execution( * service..*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/> </aop:config> <!-- 配置dataSource --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/j2ee?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true"/> <property name="user" value="root"/> <property name="password" value="wyy"/> <property name="initialPoolSize" value="5"/> <property name="maxPoolSize" value="10"/> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="model"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL57Dialect</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">true</prop> </props> </property> </bean> <!-- 配置hibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans>

3.給service的實現類新增@Service註解 給dao的實現類新增@Repository註解 將生命週期管理交給spring

注意所有交給spring管理的類,不能new出例項,只能用spring注入。

4.所有使用到service和dao的地方,均使用@Autowired註解注入。

@Autowired註解可以在建構函式、類成員屬性、getset方法添加註解注入bean,但是類成員屬性的注入方法是不推薦的

總結下來,使用屬性注入會產生如下問題

  1. 物件和注入的容器有著很緊的耦合
  2. 物件間的耦合被隱藏了,外部無法看到,不利於複雜度控制
  3. 如果沒有注入容器,物件無法建立
  4. 當一個類有多個屬性注入,你感知不到他的複雜度。而當你使用建構函式注入時,就會發現,要穿入的引數過多。也是不利於複雜度控制

5.dao的實現技術

  • sessionFactory

    @Repository
    public class UserDaoImp implements UserDao {
    
        private SessionFactory sessionFactory;
    
        @Autowired
        public UserDaoImp(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
    
        @Override
        public User get(String userId) {
            return sessionFactory.openSession().load(User.class, userId);
        }
    }
  • hibernateTemplate

    @Repository
    public class UserDaoImp implements UserDao {
    
        @Autowired
        private HibernateTemplate hibernateTemplate;
    
        public UserDaoImp(HibernateTemplate hibernateTemplate) {
            this.hibernateTemplate = hibernateTemplate;
        }
    
        @Override
        public User get(String userId) {
            return hibernateTemplate.get(User.class, userId);
        }
    }

hibernateTemplate封裝了SessionFactory,資料庫操作變得更簡單。

如下給出實現hibernateTemplate分頁的程式碼。

@Override
public List<Order> getListByHql(String hql, int page, int pageSize) {
    return hibernateTemplate.execute(new HibernateCallback<List<Order>>() {
        @Override
        public List<Order> doInHibernate(Session session) throws HibernateException {
            Query<Order> query = session.createQuery(hql);
            query.setFirstResult((page - 1) * pageSize).setMaxResults(pageSize);
            //把結果返回
            return query.list();
        }
    });
}

問題與解決

nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException

這個錯誤顯然是沒有找到某個jar包。如果要定義aop,除了spring核心包之外,還需要自行下載這兩個jar。

  • aopalliance.jar
  • aspectjweaver.jar

檢查一下jar包,發現沒有aspectjweaver.jar,下載並加入到專案路徑即可。