spring mvc integrates mybatis

1.spring configuration file:
applicationContext.xml
This configuration file needs to configure dataSource, transactionManager, sqlSessionFactory, MapperScannerConfigurer, and the interface to be used


2.web.xml configuration file
Configure the listener, when the web starts, the spring configuration file is automatically loaded
Configuration DispatcherServlet, mapping between routes and controllers 3. The

servlet configuration file mvc-dispatcher-servlet.xml
configures the basic scanning package (scanning the controller), configures mvc:resources, and configures the view parser

4. Write the controller

code , see: http://blog .csdn.net/techbirds_bao/article/details/9233599/

OR M
O: object, define a class by yourself, the attribute is private, set and get methods
R: relational relational database
M: mapping. *.hbm.cfg defines the mapping between classes and tables, and the mapping between variables and fields. When there is no column field, the default column=name
  
------------ -
Read the configuration file: (the entire project is only initialized once)
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">
<!-- Assign values ​​to properties, through the set method-->
<property name="name" value="zouhuiying"></property>
</bean>
<bean id="book" class="spring.bean.Constructor1 ">
         <!--Assignment by constructor-->
<constructor-arg value="math"></constructor-arg>
<constructor-arg value="180"></constructor-arg>
         <!--Pass index (the index of the variable in the constructor) identifier, or type (the type of the variable) -->
</bean>
![CDATA[]] special characters
<value></value>:
<bean id="book" class= "spring.bean.Constructor1">
  <constructor-arg>
    <value>![CDATA[<math^>]]</value>
  </constructor-arg>
</bean>

Internal bean
<bean id="" class="">
  <property name="">
    <!--Internal beans cannot be used externally, so the id attribute can be omitted -->
    <bean class="">
      <constructor-arg>
         <value><![CDATA[<math>*]]></value>
      </constructor-arg>
    </bean>
  </property>
</bean>
assignment It is null:
<constructor-arg><null/></constructor-arg>
Cascade property assignment (property of inner class): The property needs to be initialized before assigning a cascade property, otherwise it will be an exception
---- --------------------------------------------------
-Configure collection properties
list<car>
<property name=""> <
  list>
    <ref bean="" />
  </list>
</property>
------------
make configuration map property
<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" /> private Properties properties; Properties class Configure properties property value
---------------



<bean id="datasource" class="spring.bean.DataSource">
<property name="properties">
<props>
<prop key="user">root</prop>
<prop key="password">zouhuiying </prop>
</props>
</property>
</bean>
---------------------------------- --------------------- To
obtain beans
, first obtain the IOC container ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
that is: load the configuration file, after obtaining the IOC container , the system will automatically execute the set method and constructor of the bean in the configuration file
HelloWorld hello=(HelloWorld) ctx.getBean(HelloWorld.class); //through the class name
Constructor1 con=(Constructor1) ctx.getBean("book2"); //by id

-------------------------------------------------------- ---------- Autowire
autowire
=""

byName:set method name bean id //map bean cannot autowire
the type of byType:class. There can only be one bean
---------------------------------------------- --------------
Configured inheritance parent parent="person"
abstract="True" abstract bean cannot be instantiated
If no class is specified, the
subclass must be set to abstract="True" When writing the property of the parent class, you can only use the property

bean that the parent class has used to directly depend on
depends-on=" the id of a bean
------------------- ----------------------------------------
bean scope
using <bean></ bean> is a singleton of sscope=ingleton by default. Each call is made by the same bean
. The scope property prototype (prototype) is set. Every time a bean is used, a new bean is generated. When the IOC container is initialized, the bean is not initialized.

-------------------------------------------------- ---------
Use the external property file
spring to connect to the database, you need to configure the dataSource bean, class="datasource of the system"

<!
<context:property-placeholder location="classpath:db.properties"/>
${var}
----------------------------- ---------------------------------
spring language expression: SpEL
#{...} //... Represents SpEL, dynamic assignment
value="#{'gggggggg'}" //Direct assignment
T(): reference system function
#{T(java.lang.Math).PI * 80}
--------- -------------------------------------------------- ------
bean life cycle
init-method="init" //Write initialization and destruction methods by yourself
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 post-processor: no need to configure id, the IOC container automatically recognizes that
MyBeanPostProcessor inherits the BeanPostProcessor interface and implements the method postProcessAfterInitialization and postProcessBeforeInitialization(Object bean, String beanName)
configuration files: <bean class="spring.beans.MyBeanPostProcessor" />
------------------------ -------------------------------------------------- --------- Create Bean class Car public class StaticFactory { private static Map<String,
by calling the static factory method 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); private Map<String, Car> cars=null; public class InstanceFactory { Create Bean by calling instance factory method
----------------------------



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> ------------------------------ ------------------------------------- Configuring beans via FactoryBean
-------------------------------------------------- ----------------




Configure the scan package, multiple packages are separated by ","
<context:component-scan base-package="com.zou.service"></context:component-scan>
@Component: Basic annotation, identifying a Spring-managed The component
@Respository: identifies the persistence layer component
@Service: identifies the service layer (business layer) component
@Controller: identifies the presentation layer component
resource-pattern: filter package
<context:include-filter> The child node represents the target class to be included
<context The :exclude-filter> child node indicates that the target class to be excluded
can have several <context:include-filter> and <context:exclude-filter> under the target class <context:component-scan>. The child node
class A refers to class B. Add @Autowired (@Resource, @Inject)
@Autowired annotation to class B to automatically wire a single bean property with compatible types
Constructor , ordinary fields (even non-public), all methods with parameters can apply @Authwired annotation
By default , all properties annotated with @Authwired need to be set. When Spring cannot find a matching Bean assembly property, an exception will be thrown. If a property is allowed not to be set, You can set the required attribute of the @Authwired annotation to false
By default, when there are multiple beans of compatible types in the IOC container, autowiring by type will not work. In this case, the name of the bean can be provided in the @Qualifier annotation. Spring allows the input parameters of methods to be marked with @Qualifiter Specifying the name of the injected bean The
@Authwired annotation can also be applied to properties of an array type, in which case Spring will autowire all matching beans.
The @Authwired annotation can also be applied to collection properties, where Spring reads the collection type information, and then automatically wire all compatible beans. When the
@Authwired annotation is used on java.util.Map, if the key value of the Map is String, then Spring will automatically wire the beans that are compatible with the Map value type. At this time, the name of the bean is used as the key value

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327008760&siteId=291194637