Spring笔记整理

来源:互联网 发布:360.cn 域名价格 编辑:程序博客网 时间:2024/05/01 20:37

之前写的博客,给自己删了。。觉得还是有留着的必要,虽然写的很菜

Spring:

Helloword(And IOC)

第一个包是:spring核心jar

第二个包是日志相关包:commons-logging

 

 

相关的xml的配置:

<?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

<bean id="userDao"class="cn.jwj.dao.impl.UserDaoImpl"></bean>

 

  <bean id="userService"class="cn.jwj.service.UserService">

    <property name="userDao"ref="userDao"></property>

  </bean>

</beans>

 

注意<property>是属性注入:
name要和相关的属性名字一样,不然会出错(byname的情况下)

 

Dao层:

public interface UserDao {

    public void save(User u);

 

}

 

public class UserDaoImpl implements UserDao{

    public void save(User user){

       System.out.println("user save");

    }

 

}

 

 

 

public class UserService {

    private UserDao userDao;

 

    public UserDao getUserDao(){

       return userDao;

    }

    //set注入注意xml文件的配的属性要一致(Byname)

    public void setUserDao(UserDaouserdao) {

       this.userDao = (UserDaoImpl) userdao;

    }

   

    public void save(User u){

     userDao.save(u);

    }

}

测试:

public class test {

    @Test

    public void test1(){

       ApplicationContext  cxt=newClassPathXmlApplicationContext("bean.xml");

       UserServiceservice=(UserService) cxt.getBean("userService");

       User u=new User();

       u.setId(1);

       u.setName("zz");

       service.save(u);

      

    }

}

.scope

<beanid="userService" class="cn.jwj.service.UserService" scope="prototype">

    <propertyname="userDao" ref="userDao"></property>

  </bean>

Prototype:每次拿到的都是不一样的

 

 

 

集合

<bean id="moreComplexObject"class="example.ComplexObject">

  <!-- results in asetAdminEmails(java.util.Properties) call -->

  <propertyname="adminEmails">

    <props>

        <propkey="administrator">administrator@example.org</prop>

        <propkey="support">support@example.org</prop>

        <propkey="development">development@example.org</prop>

    </props>

  </property>

  <!-- results in asetSomeList(java.util.List) call -->

  <property name="someList">

    <list>

        <value>a list elementfollowed by a reference</value>

        <refbean="myDataSource" />

    </list>

  </property>

  <!-- results in asetSomeMap(java.util.Map) call -->

  <propertyname="someMap">

    <map>

        <entry>

            <key>

                <value>anentry</value>

            </key>

            <value>just somestring</value>

        </entry>

        <entry>

            <key>

                <value>aref</value>

            </key>

            <ref bean="myDataSource"/>

        </entry>

    </map>

  </property>

  <!-- results in asetSomeSet(java.util.Set) call -->

  <propertyname="someSet">

    <set>

        <value>just somestring</value>

        <refbean="myDataSource" />

    </set>

  </property>

</bean>

 

自动装配

Byname

<beanid="userService" class="cn.jwj.service.UserService" scope="prototype"  autowire="byName">

  </bean>

bytype

<beanid="userService" class="cn.jwj.service.UserService" scope="prototype"  autowire="byType">

</bean>

 

default-autowire="byType"

 

beans中配:全局的

 

 

要用到的时候才创建

lazy-init="true"

 

 

annotation

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
               
     <context:annotation-config/>
     
</beans>

 

<?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:context="http://www.springframework.org/schema/context"

      xsi:schemaLocation="http://www.springframework.org/schema/beans

          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context-2.5.xsd">      

<context:annotation-config/>

<bean id="userDao" class="cn.jwj.dao.impl.UserDaoImpl"></bean>

 

  <bean id="userService" class="cn.jwj.service.UserService">

  </bean>

</beans>

xmlns:context=http://www.springframework.org/schema/context

annotation的命名空间

<context:annotation-config/>

Annotation的处理器才会加载

 

 

@Autowired:自动注入默认bytype byname(@Qualifier("u"))

    public void setUserDao(@Qualifier(value="u")UserDao userdao) {

       this.userDao = (UserDaoImpl) userdao;

    }

@Qualifier:制定名字

 

通过制定的扫包加载bean有(@Component

<context:component-scanbase-package="cn.jwj"></context:component-scan>

 

@Component可以指定名字

@Scope("prototype")

public class UserService {

         private UserDao userDao;

 

         public UserDao getUserDao() {

                  return userDao;

         }

         @Resource(name=”u”)//自动注入默认byname找不到之后bytape

         public void setUserDao(UserDao userdao) {

                   this.userDao = (UserDaoImpl) userdao;

         }

         public void save(User u){

          userDao.save(u);

         }

}

@Component("u")

public class UserDaoImpl implementsUserDao{

         public void save(User user){

                   System.out.println("user save");

         }

 

}

 

AOP

Aop要的包

 

织入点语法

  • the execution of any public method:

execution(public * *(..))

  • the execution of any method with a name beginning with "set":

execution(* set*(..))

  • the execution of any method defined by the AccountService interface:

execution(* com.xyz.service.AccountService.*(..))

  • the execution of any method defined in the service package:

execution(* com.xyz.service.*.*(..))

  • the execution of any method defined in the service package or a sub-package:

execution(* com.xyz.service..*.*(..))

 

 

动态代理没有实现接口用二进制码要引入的包

 

 

 

 

@Aspect

@Component

public class Log  {

   

   

    @Before("execution(*cn.jwj.service.UserService.save(..))")

    public void dobefore(){

       System.out.println("before");

    }

 

}

Xml方式:

<aop:config>

  <aop:aspectid="myAspect" ref="aBean">

    ...

  </aop:aspect>

</aop:config>

 

<bean id="aBean" class="...">

  ...

</bean>

 

<aop:config>

         <aop:pointcutexpression="execution(*cn.jwj.service.UserService.save(..))" id="logPointcut"/>

         <aop:aspectid="logAspect" ref="log">

                   <aop:before method="dobefore"pointcut-ref="logPointcut"/>

         </aop:aspect>

</aop:config>

 

<beanid ="log" class="cn.jwj.aop.Log"></bean>

 

Datasource

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">

 

  <!-- results in a setDriverClassName(String) call -->

  <propertyname="driverClassName" value="com.mysql.jdbc.Driver"/>

  <property name="url"value="jdbc:mysql://localhost:3306/mydb"/>

  <propertyname="username" value="root"/>

  <propertyname="password" value="masterkaoli"/>

</bean>

要加入这两个包

<bean id="myDataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">

 

  <!--results in a setDriverClassName(String) call -->

  <property name="driverClassName"value="com.mysql.jdbc.Driver"/>

  <property name="url"value="jdbc:mysql://localhost:3306/spring"/>

  <property name="username"value="root"/>

  <property name="password"value="root"/>

 

然后将数据源注入dao中即可

@Component

public class UserDaoImpl implementsUserDao{

         private DataSource myDataSource;

        

         public DataSource getMyDataSource() {

                   return myDataSource;

         }

         @Resource

         public void setMyDataSource(DataSource myDataSource) {

                   this.myDataSource = myDataSource;

         }

        

         public void save(User user){

                   try {

                            Connection con= myDataSource.getConnection();

                            String sql="insert into user values(null,'zhangsan')";

                            con.createStatement().executeUpdate(sql);

                            con.close();

                           

                   } catch (SQLException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                  

         }

 

}

 

Hibernate的整合

SessionFactory:

</bean>

  <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

    <property name="dataSource"ref="myDataSource"/>

    <property name="annotatedClasses">

      <list>

        <value>cn.jwj.model.User</value>

      </list>

    </property>

    <property name="hibernateProperties">

      <props>

      <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>

     <prop key="hibernate.show_sql">true</prop>

     

      </props>

    </property>

  </bean>

 

org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean

支持annotation

 

@Component

public class UserDaoImpl implementsUserDao{

         private SessionFactory sessionFactory;

        

        

         public SessionFactory getSessionFactory() {

                   return sessionFactory;

         }

 

         @Resource

         public void setSessionFactory(SessionFactorysessionFactory) {

                   this.sessionFactory = sessionFactory;

         }

         public void save(User user){ 

                    Session sessionsessionFactory.openSession();

                    session.beginTransaction();

                    session.save(user);

                    session.getTransaction().commit();

                    session.close();

}sessionfactory注入到dao

@Transactional

<!-- from the file 'context.xml' -->

<?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:tx="http://www.springframework.org/schema/tx"

     xsi:schemaLocation="

    http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd

    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

    http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

  <bean id="fooService"class="x.y.service.DefaultFooService"/>

  <tx:annotation-driventransaction-manager="txManager"/>

  <bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

  <propertyname="dataSource" ref="dataSource"/>

  </bean>

</beans>

 

 

 

 

 

 

首先得加入命名空间:

xmlns:tx="http://www.springframework.org/schema/tx

 http://www.springframework.org/schema/tx

 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

1.      生成bean( txManager)

<bean id="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">

  <property name="sessionFactory"ref="mySessionFactory"/></bean>

2事务的管理交予这个bean管理

<tx:annotation-driventransaction-manager="txManager"/>

      

Session session= sessionFactory.getCurrentSession();//事务的管理就由txManager管理了

//现在也能拿到currentSession了        

                    session.save(user);

//关闭等操作都不用手动了

遇到runtimeException自动回滚

@Transactional(propagation=Propagation.REQUIRED)

REQUIRED(如果有transaction了不再生成新的,用调用者的transaction)

Xml:声明式事务管理

  <bean id="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">

  <property name="sessionFactory"ref="mySessionFactory"/></bean>

  <!--  <tx:annotation-driventransaction-manager="txManager"/> -->

  

    <aop:config>

    <aop:pointcut id="serviceOperation"  

         expression="execution(public* cn.jwj.service..*.*(..))"/>

    <aop:advisor pointcut-ref="serviceOperation"advice-ref="txAdvice"/>

  </aop:config>

 

   <tx:advice id="txAdvice"transaction-manager="txManager">

    <tx:attributes>

      <tx:method name="get*"read-only="true"/>

      <tx:method name="save*"propagation="REQUIRED"/>

    </tx:attributes>

  </tx:advice>

 

网上找了相关概念梳理AOP

AOP基本概念

 连接点(Joinpoint):

   表示需要在程序中插入横切关注点的扩展点,连接点可能是类初始化、方法执行、方法调用、字段调用或处理异常等等,Spring只支持方法执行连接点,在AOP中表示为“在哪里做”

切入点(Pointcut):

   选择一组相关连接点的模式,即可以认为连接点的集合,Spring支持perl5正则表达式和AspectJ切入点模式,Spring默认使用AspectJ语法,在AOP中表示为“在哪里做的集合”

增强(Advice):或称为增强

   在连接点上执行的行为,增强提供了在AOP中需要在切入点所选择的连接点处进行扩展现有行为的手段;包括前置增强(before advice)、后置增强 (after advice)、环绕增强 (around advice),在Spring中通过代理模式实现AOP,并通过拦截器模式以环绕连接点的拦截器链织入增强 ;在AOP中表示为“做什么”;

方面/切面(Aspect):

     横切关注点的模块化,比如上边提到的日志组件。可以认为是增强、引入和切入点的组合;在Spring中可以使用Schema和@AspectJ方式进行组织实现;在AOP中表示为“在哪里做和做什么集合”;

目标对象(Target Object):

   需要被织入横切关注点的对象,即该对象是切入点选择的对象,需要被增强的对象,从而也可称为“被增强对象”;由于Spring AOP 通过代理模式实现,从而这个对象永远是被代理对象,在AOP中表示为“对谁做”

AOP代理(AOP Proxy):

   AOP框架使用代理模式创建的对象,从而实现在连接点处插入增强(即应用切面),就是通过代理来对目标对象应用切面。在Spring中,AOP代理可以用JDK动态代理或CGLIB代理实现,而通过拦截器模型应用切面。

织入(Weaving):

   织入是一个过程,是将切面应用到目标对象从而创建出AOP代理对象的过程,织入可以在编译期、类装载期、运行期进行。

引入(inter-typedeclaration):

   也称为内部类型声明,为已有的类添加额外新的字段或方法,Spring允许引入新的接口(必须对应一个实现)到所有被代理对象(目标对象), 在AOP中表示为“做什么(新增什么)”

 

AOP的Advice类型

前置增强(Before advice):

   在某连接点之前执行的增强,但这个增强不能阻止连接点前的执行(除非它抛出一个异常)。

后置返回增强(After returningadvice):

   在某连接点正常完成后执行的增强:例如,一个方法没有抛出任何异常,正常返回。

后置异常增强(After throwingadvice):

   在方法抛出异常退出时执行的增强。

后置最终增强(After (finally)advice):

   当某连接点退出的时候执行的增强(不论是正常返回还是异常退出)。

环绕增强(Around Advice):

   包围一个连接点的增强,如方法调用。这是最强大的一种增强类型。 环绕增强可以在方法调用前后完成自定义的行为。它也会选择是否继续执行连接点或直接返回它们自己的返回值或抛出异常来结束执行

 

 

 

 

 

 

 

 

 

 

记录之前小Demo的xml:

<?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:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xmlns:tx="http://www.springframework.org/schema/tx"

                    xsi:schemaLocation="http://www.springframework.org/schema/beans

            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

             http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd

           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">      

<context:annotation-config/>

 <context:component-scanbase-package="cn.jwj"></context:component-scan>

 

<aop:config>

         <aop:pointcutexpression="execution(*cn.jwj.service.UserService.save(..))" id="logPointcut"/>

         <aop:aspect id="logAspect"ref="log">

                   <aop:before method="dobefore"pointcut-ref="logPointcut"/>

         </aop:aspect>

</aop:config>

 

<bean id ="log"class="cn.jwj.aop.Log"></bean>

 

<!-- <beanid="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">

 

 

  <property name="driverClassName"value="com.mysql.jdbc.Driver"/>

  <property name="url"value="jdbc:mysql://localhost:3306/spring"/>

  <property name="username"value="root"/>

  <property name="password"value="root"/>

 

</bean> -->

 

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <property name="locations">

        <value>classpath:jdbc.properties</value>

    </property>

</bean>

 

<bean id="myDataSource"destroy-method="close"

     class="org.apache.commons.dbcp.BasicDataSource">

    <property name="driverClassName"value="${jdbc.driverClassName}"/>

    <property name="url"value="${jdbc.url}"/>

    <property name="username"value="${jdbc.username}"/>

    <property name="password"value="${jdbc.password}"/>

</bean>

  <bean id="mySessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

    <property name="dataSource"ref="myDataSource"/>

    <property name="annotatedClasses">

      <list>

        <value>cn.jwj.model.User</value>

      </list>

    </property>

    <property name="hibernateProperties">

      <props>

      <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>

     <prop key="hibernate.show_sql">true</prop>

     

      </props>

    </property>

  </bean>

  <bean id="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">

  <property name="sessionFactory"ref="mySessionFactory"/></bean>

  <!--  <tx:annotation-driventransaction-manager="txManager"/> -->

  

    <aop:config>

    <aop:pointcut id="serviceOperation"  

         expression="execution(public* cn.jwj.service..*.*(..))"/>

    <aop:advisorpointcut-ref="serviceOperation"advice-ref="txAdvice"/>

  </aop:config>

 

   <tx:advice id="txAdvice"transaction-manager="txManager">

    <tx:attributes>

      <tx:method name="get*"read-only="true"/>

      <tx:method name="save*"propagation="REQUIRED"/>

    </tx:attributes>

  </tx:advice>

 

 </beans>

 

packagesToScan 

<property name="packagesToScan">

   <list><value>cn.jwj.model</value></list>

   </property>

就不用配置Entity的class了,自动扫包

HibernateTemplate

设计模式:Template Method

Callback:回调/钩子函数(你挂什么它就执行什么)

 

首先要生成bean放到IOCe容器中

<bean id="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">

    <property name="sessionFactory"ref="mySessionFactory"></property>

  </bean>

将HibernatTemplate注入到daoImpl中

         private HibernateTemplate hibernateTemplate;

         public HibernateTemplategetHibernateTemplate() {

                   return hibernateTemplate;

         }

         @Resource

         public voidsetHibernateTemplate(HibernateTemplate hibernateTemplate) {

                   this.hibernateTemplate = hibernateTemplate;

         }

         public voidsave(User user){ 

                   hibernateTemplate.save(user);

 

HibernateDaoSupport

封装了hibernatetemplate的类用于继承的类。方法都是final不能重写

 

如果一个类继承了HibernateDaoSupport 必须注入sessionFactory或者是Hibernatetemplate

以下是xml的注入方法:

<bean id="dao"class="cn.jwj.dao.impl.UserDaoImpl">

  <property name="sessionFactory"ref="mySessionFactory"></property>

  </bean>

Dao是UserDaoImpl

使用继承中的属性Hibernatetemplate即可完成常用的方法

this.getHibernateTemplate().save(user);

 

但是这种的方法每次都要为继承HibernateDaoSupport的类注入HibernateTemplate或者sessionFactory 所以可以使用另外一种方法

就是:生成一个类继承HibernateDaoSupport类,虽然不能重写Set等方法,但是可以添加一个方法,在调用super父类的set方法注入属性。然后其他类再继承这个类就可以直接使用Annotation了

建议注入sessionFactory

 

@Component("SuperDao")

public class SuperDao extends HibernateDaoSupport {

    @Resource(name="mySessionFactory")

    public voidsetSuperSessionFactory(SessionFactory sessionFactory){

       super.setSessionFactory(sessionFactory);

    }  

}

然后其他类可以直接继承这个类就可以:

public class UserDaoImpl extends SuperDao implements UserDa


0 0
原创粉丝点击