idea project add spring

Configuration steps

1. Add the dependency package of spring

Idea can directly right-click the project to select add frame support, check spring

2. Create applicationContext.xml

Create applicationContext.xml in direct subdirectory of src

An example of applicationContext.xml is given here, along with annotation explanations

<?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. Add the @Service annotation to the implementation class of the service Add the @Repository annotation to the implementation class of the dao to hand over the life cycle management to spring

Note that all classes managed by spring cannot create new instances, but can only be injected with spring.

4. All places where service and dao are used are injected with @Autowired annotation.

The @Autowired annotation can add annotations to the constructor, class member properties, and getset methods to inject into beans, but the injection method of class member properties is not recommended


Someone on stackoverflow explained it in detail https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it

To sum up, using property injection will cause the following problems

  1. Objects and injected containers are tightly coupled
  2. The coupling between objects is hidden and cannot be seen from the outside, which is not conducive to complexity control
  3. Object cannot be created without injecting into the container
  4. When a class has multiple properties injected, you cannot perceive its complexity. And when you use constructor injection, you will find that there are too many parameters to pass through. It is also not conducive to complexity control

5. The realization technology of 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 encapsulates the SessionFactory, making database operations easier.

The code to implement hibernateTemplate paging is given below.

@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();
        }
    });
}

problem and solution

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

This error is obviously that a jar package was not found. If you want to define aop, in addition to the spring core package, you need to download these two jars yourself.

  • aopalliance.jar
  • aspectjweaver.jar

Check the jar package and find that there is no aspectjweaver.jar, just download and add it to the project path.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325672162&siteId=291194637