spring mvc整合mybatis

1.spring配置文件:
applicationContext.xml
该配置文件里需配置dataSource、transactionManager、sqlSessionFactory、MapperScannerConfigurer、所要用到的接口


2.web.xml配置文件
配置监听器,当web启动时,自动加载spring配置文件
配置DispatcherServlet,路由与controller的映射

3.servlet配置文件mvc-dispatcher-servlet.xml
配置基础扫描包(扫描controller),配置mvc:resources,配置视图解析器

4.写控制器

代码参见: http://blog.csdn.net/techbirds_bao/article/details/9233599/

OR M
O:对象,自己定义一个class,属性为private ,set与get方法
R:relational关系型数据库
M:mapping。*.hbm.cfg定义类与表的映射,变量与字段的映射,当没有column字段时,默认column=name
  
-----------------------
读取配置文件:(整个工程只初始化一次)
Configuration cfg=new Configuration();
cfg.configure("config.cfg.xml");
SessionFactory sessionFactory=cfg.buildSessionFactory();

--------------
模板代码
Session session=null;
Transaction tx=null;
try{
    session=sessionFactory.openSession();
    tx=session.beginTransaction();
    ..............代码
    tx.commit();
}catch(Exception e){
    if(tx!=null){
        tx.rollback();
     }
     throw e;

}finally{
      if(session!=null)session.close();
}
---------------------------------------------------------
在*.xml配置文件中设置bean
<bean id="helloWorld" class="spring.bean.HelloWorld">
<!-- 为属性赋值 ,通过set方法-->
<property name="name" value="zouhuiying"></property>
</bean>
<bean id="book" class="spring.bean.Constructor1">
         <!--通过构造方法赋值-->
<constructor-arg value="math"></constructor-arg>
<constructor-arg value="180"></constructor-arg>
         <!--通过index(构造方法中变量的索引)标识,或者type(变量的类型)-->
</bean>
![CDATA[]]特殊字符
<value></value>:
<bean id="book" class="spring.bean.Constructor1">
  <constructor-arg>
    <value>![CDATA[<math^>]]</value>
  </constructor-arg>
</bean>

内部bean
<bean id="" class="">
  <property name="">
    <!--内部bean不能被外部使用,所以可以不加id属性-->
    <bean class="">
      <constructor-arg>
         <value><![CDATA[<math>*]]></value>
      </constructor-arg>
    </bean>
  </property>
</bean>
赋值为null:
<constructor-arg><null/></constructor-arg>
级联属性赋值(内部类的属性):属性需要先初始化后,才可以为级联属性赋值,否则处异常
-------------------------------------------------------
配置集合属性
list<car>
<property name="">
  <list>
    <ref bean="" />
  </list>
</property>
------------
使配置map属性
<property name="">
<map>
  <entry key="" value-ref="">
  </entry>
</map>
</property>
-------------
<bean>
  <property>
    <props>
      <prop key="">value</prop>
      <prop key="">value</prop>
    </props>
  </property>
</bean>
-------------
配置单例的集合bean
<property name="car" ref="cars">
<util:list id="cars">
<ref bean="car1"/>
<ref bean="car2"/>
</util:list>
------------

p:命名空间
xmlns:p="http://www.springframework.org/schema/p"
<bean id="person2" class="spring.bean.Person" p:name="baobao" p:age="23" p:car-ref="car1" />
---------------
配置properties属性值
Properties类
private Properties properties;
<bean id ="datasource" class="spring.bean.DataSource">
<property name="properties">
<props>
<prop key="user">root</prop>
<prop key="password">zouhuiying</prop>
</props>
</property>
</bean>
-------------------------------------------------------
获取bean
首先获取IOC容器ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
即:加载配置文件,获取IOC容器后,系统会自动执行配置文件中bean的set方法和构造函数
HelloWorld hello=(HelloWorld) ctx.getBean(HelloWorld.class); //通过类名
Constructor1 con=(Constructor1) ctx.getBean("book2");//通过id

--------------------------------------------------------
自动装配
autowire=""

byName:set方法的名字bean的id //map bean不能自动装配
byType:class的类型。只能有一个bean
-----------------------------------------------------------
配置的继承parent  parent="person"
abstract="True" 抽象bean不能被实例化
如果没有指定class,必须要设置abstract="True"
子类重写父类的property时,只能用父类已经用过的属性

bean直接的依赖
depends-on="某个bean的id
-----------------------------------------------------------
bean的作用域
使用<bean></bean>是默认是sscope=ingleton单例,每次调用都是同一个bean
设置scope属性prototype(原型)每次用bean时,都是产生一个新的bean,初始化IOC容器时,并不初始化该bean

-----------------------------------------------------------
使用外部属性文件
spring要连接数据库,需要配置dataSource bean,class="系统的datasource"

<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties"/>
${var}
--------------------------------------------------------------
spring语言表达式:SpEL
#{...} //...代表SpEL,动态赋值
value="#{'gggggggg'}" //直接赋值
T():引用系统函数
#{T(java.lang.Math).PI * 80}
-----------------------------------------------------------------
bean生命周期
init-method="init"  //自己写初始化和销毁方法
destroy-method="destroy"
ClassPathXmlApplicationContext对象有个close方法
ApplicationContext没有close放法

public static void main(String[] args) {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beanss.xml");
        Car car=(Car) ctx.getBean("car");
        System.out.println(car);
        ctx.close();
}
<bean id="car" class="spring.beans.Car" p:brand="Audi" p:color="red" init-method="init" destroy-method="destroy" />
bean的后置处理器:不需要配置id,IOC容器自动识别
MyBeanPostProcessor继承BeanPostProcessor接口,实现方法postProcessAfterInitialization与postProcessBeforeInitialization(Object bean, String beanName)
配置文件:<bean class="spring.beans.MyBeanPostProcessor" />
-----------------------------------------------------------------------------------
通过调用静态工厂方法创建 Bean
class Car
public class StaticFactory {
private static Map<String, Car> cars=new HashMap<String, Car>();
static{
cars.put("car1", new Car("house","red"));
cars.put("car2", new Car("audi","white"));

}
public static Car getCar(String name){
return cars.get(name); //调用的是car的工厂方法
}
}
配置文件:
<bean id="car1" class="springfactory.StaticFactory" factory-method="getCar">
  <constructor-arg value="car1"></constructor-arg>
</bean>
main函数
ApplicationContext ctx=new ClassPathXmlApplicationContext("factory.xml");
Car car=(Car)ctx.getBean("car1");
System.out.println(car);
----------------------------
通过调用实例工厂方法创建 Bean
public class InstanceFactory {
private Map<String, Car> cars=null;
public InstanceFactory() {
super();
cars=new HashMap<String, Car>();
cars.put("one", new Car("ford","yellow"));
cars.put("two", new Car("anta","green"));
}
public Car getCar(String name) {
return cars.get(name);
}
配置文件:
<!-- 配置实例工厂 -->
<bean id="factory" class="springfactory.InstanceFactory"></bean>
<bean id="car2" factory-bean="factory" factory-method="getCar">
<constructor-arg value="two"></constructor-arg>
</bean>
------------------------------------------------------------------
通过FactoryBean配置bean


-------------------------------------------------------------------
配置扫描包,多个包用“,”分隔
<context:component-scan base-package="com.zou.service"></context:component-scan>
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件
resource-pattern :过滤包
<context:include-filter> 子节点表示要包含的目标类
<context:exclude-filter> 子节点表示要排除在外的目标类
<context:component-scan> 下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点
A类引用B类,在B类上加 @Autowired (@Resource 、@Inject)
@Autowired 注解自动装配具有兼容类型的单个 Bean属性
构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解
默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false
默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称
@Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.
@Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean.
@Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值

猜你喜欢

转载自zouhuiying.iteye.com/blog/2288872